dongyan3237 2013-01-31 15:48
浏览 28
已采纳

MySQL - 从多个表中选择,可能没有连接?

It's been a while since I needed help, but today I'm here to basically get assistance from your knowledge. I'm currently quite stuck on a very annoying SQL problem, which is the following.

I have two tables. Painteditems, and specialitems. Both tables have unique column names (painteditemid, specialitemid etc), yet both tables share similar values. I want to get results from both tables.

Let's say this is my setup:

PaintedItems

  • paintedItemName
  • paintedItemColor
  • visible

SpecialItems

  • specialItemName
  • specialItemColor
  • visible

I used this query:

SELECT *
FROM `painteditems` AS pa,
     `specialitems` AS sp
WHERE (pa.`visible` = 1
       OR sp.`visible` = 1)
  AND (pa.`painteditemname` = 'itemname1'
       OR sp.`specialitemname` = 'itemname1')
  AND (pa.`painteditemcolor` = 'black'
       OR sp.`specialitemcolor` = 'black')

That resulted in:

Showing rows 0 - 29 ( 259,040 total, Query took 39.4352 sec)

even though both tables contain only 10.000 rows altogether. Adding this did nothing:

GROUP BY pa.`painteditemid`, sp.`specialitemid`

Still 260k rows. How should I approach this?

Thank you in advance.

edit: fixed spacing, code blocks

  • 写回答

3条回答 默认 最新

  • dongmao7195 2013-01-31 15:52
    关注

    Sure sounds like you want a UNION between the two tables. Right now, you are getting a cartesian product which is why the results are so large:

    select *, 'painted' Source
    from painteditems
    where visible = 1
        and painteditemname = 'itemname1'
        and painteditemcolor = 'black'
    union all
    select *, 'special' Source
    from specialitems
    where visible = 1
        and specialitemname = 'itemname1'
        and specialitemcolor = 'black'
    

    You will need to replace the SELECT * with your column names. Also the number of columns and datatypes must match in both queries.

    UNION ALL will return all rows from both tables, if you only want DISTINCT rows then you will want to use UNION

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂