K
K
Kolya Vantukh2018-04-01 12:11:32
MySQL
Kolya Vantukh, 2018-04-01 12:11:32

How to correctly form an sql query with an n: n connection?

There are 3 tables:
users , wallets , wallet_address .
A user may or may not have a value of some addresses to wallets .
A relationship of users to wallets is many to many .
wallet_address, in addition to the user_id and wallet_id fields, there is also value (namely, the wallet address itself)
The problem is that I can’t figure out how to generate an sql query to select all wallets in the system and, provided that the user has an address to the wallet, display this address. For example, the output of all application wallets:

foreach($wallets as $wallet) {
    echo $wallet['name'];
    echo $wallet['wallet_address'] //конкретный адрес , который добавил юзер(если нет , то null)
}

It feels like this problem has already been solved many times, I can not understand how. Tell me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexalexes, 2018-04-01
@alexalexes

What's the problem?
users is one set;
wallets is another set;
wallet_address - intersection of sets (table with chords [user_id, wallet_id]).
You just need to glue all the tables according to the corresponding keys and display those records from users that intersect with wallets records with a non-empty value.

select u.user_id, w.wallet_id, wa.value as address
  from users u
   join wallet_address wa on wa.user_id = u.user_id
   join wallets w on w.wallet_id = wa.wallet_id
where wa.value is not null

PS: Are you sure that the wallet address should be determined by the [user_id, wallet_id] combination, isn't this an independent wallet property, that is, a specific wallets record?
If so, then value will refer to wallets, and the wallet_address table will not refer to an address, it will simply store the two foreign keys user_id and wallet_id to only serve the function of storing n:n intersection chords.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question