如何找到给定的值出现在mysql中有多少个表中

时间:2015-10-30 04:56:07

标签: mysql sql

我有5张桌子。

给定折扣值,我想查找折扣值是否显示在多少个表中(5个中)。是否在所有5个表中?或只是在2个表等。

例如:让我们说12%的折扣。我想检查12%是否存在多少个表(5个表中)

注意:折扣值仅在给定表格中出现一次(唯一折扣)

有人可以帮助我:)

表格

table1(userid,discount)  
table2(userid,discount)    
table3(userid,discount)    
table4(userid,discount)    
table5(userid,discount)

3 个答案:

答案 0 :(得分:3)

您可以使用的唯一选项是与所有表格保持联接,这些表格将为您提供数据所在的表格

答案 1 :(得分:0)

这可能会有所帮助。

 with CTE(col1,col2,col3,col4,col5)
 AS
 ((select CASE when count(1) >0 then 1 else 0 end 
from table1
where discount=@discount)  ,
(select CASE when count(1) >0 then 1 else 0 end 
from table2
where discount=@discount),
(select CASE when count(1) >0 then 1 else 0 end 
from table3
where discount=@discount),
(select CASE when count(1) >0 then 1 else 0 end 
from table4
where discount=@discount),
(select CASE when count(1) >0 then 1 else 0 end 
from table5
where discount=@discount)) 

select col1+col2+col3+col4+col5 from CTE

答案 2 :(得分:0)

您可以使用UNION

SELECT COUNT(*) AS numOfDiscounts
FROM (
   SELECT discount 
   FROM table1
   WHERE discount = 12

   UNION ALL

   SELECT discount 
   FROM table2
   WHERE discount = 12

   UNION ALL

   SELECT discount 
   FROM table3
   WHERE discount = 12
   UNION ALL

   SELECT discount 
   FROM table4
   WHERE discount = 12

   UNION ALL

   SELECT discount 
   FROM table5
   WHERE discount = 12) AS t

上面的查询给出了包含discount = 12行的表的数量。

Demo here

或者,您可以使用:

SELECT COALESCE((SELECT COUNT(*) FROM table1 WHERE discount = 12),0) + 
       COALESCE((SELECT COUNT(*) FROM table2 WHERE discount = 12),0) + 
       COALESCE((SELECT COUNT(*) FROM table3 WHERE discount = 12),0) + 
       COALESCE((SELECT COUNT(*) FROM table4 WHERE discount = 12),0) + 
       COALESCE((SELECT COUNT(*) FROM table5 WHERE discount = 12),0) AS numOfDiscounts

Demo here

或:

SELECT (SELECT COUNT(CASE WHEN discount=12 THEN 1 END) FROM table1) + 
       (SELECT COUNT(CASE WHEN discount=12 THEN 1 END) FROM table2) + 
       (SELECT COUNT(CASE WHEN discount=12 THEN 1 END) FROM table3) + 
       (SELECT COUNT(CASE WHEN discount=12 THEN 1 END) FROM table4) + 
       (SELECT COUNT(CASE WHEN discount=12 THEN 1 END) FROM table5) AS numOfDiscounts

Demo here