简体   繁体   中英

MySQL - Display null column from child table if all values are not distinct

I have the following tables, for example:

invoices

ID Name
1   A
2   B
3   C
4   D
5   E

transactions

ID  Invoice_ID User_ID
1       1        10
2       1        10
3       1        10
4       2        30
5       3        20
6       3        40
7       2        30
8       2        30
9       4        40
10      3        50

Now I want to make a select that will pull the invoices and the user_id from the related transactions, but of course if I do that I won't get all the ids, since they may be distinct but there will be only one column for that. What I want to do is that if there are distinct User_ids, I will display a pre-defined text in the column instead of the actual result.

select invoices.id, invoices.name, transactions.user_id(if there are distinct user_ids -> return null)

from invoices
left join transactions on invoices.id = transactions.invoice_id

and then this would be the result

ID Name User_ID
1   A    10
2   B    30
3   C    null
4   D    40
5   E    null

Is this possible?

You can do the following :

select 
   invoices.id, 
   invoices.name, 
   IF (
      (SELECT COUNT(DISTINCT user_id) FROM transactions WHERE transactions.invoice_id = invoices.id) = 1, 
      (SELECT MAX(user_id) FROM transactions WHERE transactions.invoice_id = invoices.id), 
      null
   ) AS user_id
from invoices

Or, alternatively, you can use the GROUP_CONCAT function to output a comma-separated list of users for each invoice. It is not exactly what you asked, but maybe in fact it will be more useful :

select 
    invoices.id, 
    invoices.name, 
    GROUP_CONCAT(DISTINCT transactions.user_id SEPARATOR ',') AS user_ids
from invoices
left join transactions on invoices.id = transactions.invoice_id
group by invoices.id

Try somethingh like:

select i.id, i.name, t.user_id
from invoices i left join
(
   select invoice_ID, User_ID
   from transactions
   group by invoice_ID
   having count(invoice_ID)=1
) t on i.id=t.invoice_id

SQL fiddle

You could list all the transactions that have multiple user ids, like this:

select invoices.id, invoices.name, null

from invoices
left join transactions on invoices.id = transactions.invoice_id having count(distinct transactions.user_id) > 1

Also, I think this CASE might suit your needs here:

select invoices.id, invoices.name, 
   case when count(distinct transactions.user_id) > 1 then null else transactions.user_id end     
from invoices
left join transactions on invoices.id = transactions.invoice_id 
group by invoices.id

although, I'm not sure this is syntactically correct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM