从子查询中选择“最佳结果”?

时间:2015-02-05 17:27:56

标签: mysql sql

SELECT * FROM table1
WHERE col1 = ANY (
    SELECT DISTINCT col2 FROM table2
    WHERE first = 'blah'
    OR second = 'blahblah'
    OR third = 'blahblahblah' );

子查询检查三列(firstsecondthird)。在这个例子中,我使用ANY,但我希望它像这样返回:

If found `first` return `first`
else if found `second` return `second`
else if found `third` return `third`

知道我在说什么吗?我只能选择优先级firstsecondthird

的1行(最佳)

3 个答案:

答案 0 :(得分:2)

我想你想要这个:

SELECT * FROM table1
WHERE col1 = (
    SELECT col2 FROM table2
    WHERE first = 'blah'
    OR second = 'blahblah'
    OR third = 'blahblahblah'
    ORDER BY
    first = 'blah' DESC,
    second = 'blahblah' DESC,
    third = 'blahblahblah' DESC
    LIMIT 1
);

答案 1 :(得分:0)

这样做你想要的吗?

SELECT t.*, 'first'
FROM table1 t
WHERE col1 IN (SELECT col2 FROM table2 WHERE first = 'blah')
UNION ALL
SELECT t.*, 'second'
FROM table1 t
WHERE col1 IN (SELECT col2 FROM table2 WHERE first <> 'blah' AND second = 'blahblah')
UNION ALL
SELECT t.*, 'third'
FROM table1 t
WHERE col1 IN (SELECT col2 FROM table2 WHERE first <> 'blah' AND second <> 'blahblah' AND third = 'blahblahblah' );

对于每场比赛(基于col1),它返回三个条件中的第一个。

答案 2 :(得分:0)

试试这个,

&#13;
&#13;
SELECT *, COALESCE(first, second, third) as best FROM tab
&#13;
&#13;
&#13;