MySQL - 如果所有值都不相同,则显示子表中的空列

时间:2016-04-19 15:38:31

标签: mysql

我有以下表格,例如:

发票

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

交易

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

现在我想制作一个将相关交易中的发票和user_id拉出来的选择,但当然如果我这样做,我就不会得到所有的ID,因为它们可能是截然不同的但是会有只有一列。我想要做的是,如果有不同的User_id,我将在列中显示预定义的文本而不是实际的结果。

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

然后这将是结果

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

这可能吗?

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

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

或者,您也可以使用GROUP_CONCAT功能为每张发票输出以逗号分隔的用户列表。这不完全是你问的,但事实上它可能会更有用:

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

答案 1 :(得分:2)

尝试类似的事情:

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

答案 2 :(得分:2)

您可以列出具有多个用户ID的所有事务,如下所示:

select invoices.id, invoices.name, null

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

此外,我认为CASE可能符合您的需求:

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

虽然,我不确定这在语法上是否正确