douji9816 2017-06-06 16:56
浏览 40
已采纳

在数据库中搜索内容(2) - 选择 - 需要在2个表中搜索

enter image description here As you can see in the print screen above, I am wondering, if it is possible to check if there is one thing in two tables at once WITH gaining whole one row if found (logical 1). Without making 2 queries. I need to look, if "fajne-to-jest" is in table1 or table2, and then take data row. I'm doing it in 2 queries... but question is, is it possible to check this information using one query? Mabye something else? Most efficent way? The best way?

@Gordon Linoff gave me this:

select (exists (select 1 from table1 where url = 'fajne-to-jest')) as in_table1,
       (exists (select 1 from table2 where url = 'fajne-to-jest')) as in_table2;

But this produces: enter image description here

And I want query to produce this + data from this row, like this: enter image description here

  • 写回答

1条回答 默认 最新

  • dth62818 2017-06-06 17:53
    关注

    Here's a quick stab at this, haven't tested it at all:

    select 
        IF(table1.id IS NULL, 0, 1) as table1,
        IF(table2.id IS NULL, 0, 1) as table2,
        COALESCE(table1.id, table2.id, "NONE") as id,
        `master`.url
    from
    (select 'fajne-to-jest' as url)  `master`
    left join table1 on table1.url = `master`.url
    left join table2 on table2.url = `master`.url
    ;
    

    Should always give a single row, whether it's found in 0,1, or both tables. You said url is unique so shouldn't need to worry about repeats, but if IDs don't match then this favors table1 (and prints "NONE" if not in either table).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度