SQL: Make colors from color-table searchable

别等时光非礼了梦想. 提交于 2019-12-24 16:19:44

问题


I have a database with cards of different colors.

A Card can be "Colorless" or one or more colors: "Red","Green","White","Blue","Black"

The cards is in a Card table with id, name and some other card info,

and the colors is in a Color table with name(ex:"Red"), a color code(ex:"r") and a color id

And there are a Connection table with card_id and color_id

So the question is how do a make colors searchable?

I like to be able to find all card that are "only Red",
aswell as all cards that are "Red or Blue",
and all cards that are "Red and Blue" (and the same for 3,4 and 5 colors!)

There are 30 different combinations of color:

//000001//000010//000011//000100//000101//000110//000111
//001000//001001//001010//001011//001100//001101//001111
//010000//010001//010010//010011//010100//010101//010110
//010111//011000//011001//011010//011011//011100//011101
//011111
//100000 (Colorless)

I have found out that this is posible with UNION but
one have to make all 30 different combinations and then UNION them all together!

SELECT 
c.id
'false' AS Colors,
'true' AS Red, 
'false' AS Blue
'false' AS Green
'false' AS White
'false' AS Black
'false' AS Colorless
FROM cards_data AS c
INNER JOIN con_cards_colors AS ccc_red ON c.id = ccc_red.cards_id
INNER JOIN colors AS co_red ON co_red.id = ccc_red.colors_id
WHERE
    co_red.name = "Red"

Union
(...)

This dosnt seem like a good solution!

So any idears will be appreciated?

(Optimal I like some kind of a SQL View..)


回答1:


You'd use conditional aggregations here. For Red and Blue for example you want to find cards where

  1. both colors exist
  2. no other color exists

That means if I count Red and Blue for a card I must get 2. If I count all colors I must also get 2. (Same for one, three or more colors.)

So use this query and only change the colors mentioned and the number of colors:

select *
from cards_data where id in
(
  select cards_id
  from con_cards_colors
  group by cards_id
  having count(case when colors_id in (select id from colors where name in ('Red','Blue')) then 1 end) = 2 -- i.e. find all
  and count(*) = 2 -- i.e. find only those and no others
);


来源:https://stackoverflow.com/questions/27920494/sql-make-colors-from-color-table-searchable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!