在多列中搜索MySQL并查找哪些列匹配

时间:2012-05-02 20:50:14

标签: mysql

我需要一些关于如何实现这一目标的建议。如果我有一个像这样的查询 SELECT * FROM catalog WHERE record_id = $ var OR form_id = $ var;

我想要做的是知道哪个列匹配。是记录还是形式?

3 个答案:

答案 0 :(得分:4)

也许是这样的:

select a,b,c, 1 from catalog where record_id = $var
union
select a,b,c, 2 from catalog where form_id = $var

然后1或2告诉你哪个是哪个。

答案 1 :(得分:1)

SELECT *, 
CASE
    WHEN record_id = $var and form_id = $var THEN 'both'
    WHEN record_id = $var THEN 'record_id'
    WHEN form_id = $var   THEN 'form_id'
    ELSE 'none'     -- can't happen becouse of where clause
END CASE  as how_it_was
FROM catalog WHERE record_id = $var OR form_id = $var;

请注意$ var

上的sql注入

答案 2 :(得分:1)

select *,
case when record_id = $var then 1 else 2 end as matches 
from table
where record_id = $var or form_id = $var