2016-12-02 130 views
5

以下是客戶在庫中讀取的各種書籍的列表。這些值以2的冪的形式存儲在名爲bookType的列中。MySQL查詢使用邏輯操作獲取數據列表

List of customer reading books

我需要誰從邏輯操作查詢數據庫中讀取 only Novel Or only Fairytale Or only BedTime Or both Novel + Fairytale 人的組合來獲取圖書清單。

取列表中爲以下組合:

  • 人誰讀取唯一新穎(在DB存儲爲1)
  • 人誰讀取既新穎又童話(在DB存儲爲1 + 2 = 3 )
  • 人誰讀取所有三個即{新穎+童話+就寢時間}(存儲在DB爲1 + 2 + 4 = 7)

的這些計數存儲在d在一個叫的BookType柱atabase(圖用紅色標出。)

如何使用MySQL查詢

從例如我取上面的列表,我需要獲取像新穎讀者用戶(1,3- ,5,7)。

+1

我會從調查枚舉和集合開始 - 甚至是連接表。 MySQL有更好的方式來存儲這種類型的信息。 –

回答

1

這個問題的核心是將十進制轉換爲二進制,而mysql只有一個函數 - CONV(num,from_base,to_base); 在這種情況下from_base將是10和to_base將是2. 我將在UDF 包裝這個所以給定

MariaDB [sandbox]> select id,username 
    -> from users 
    -> where id < 8; 
+----+----------+ 
| id | username | 
+----+----------+ 
| 1 | John  | 
| 2 | Jane  | 
| 3 | Ali  | 
| 6 | Bruce | 
| 7 | Martha | 
+----+----------+ 
5 rows in set (0.00 sec) 

MariaDB [sandbox]> select * from t; 
+------+------------+ 
| id | type  | 
+------+------------+ 
| 1 | novel  | 
| 2 | fairy Tale | 
| 3 | bedtime | 
+------+------------+ 
3 rows in set (0.00 sec) 

該UDF

drop function if exists book_type; 
delimiter // 

CREATE DEFINER=`root`@`localhost` FUNCTION `book_type`(
    `indec` int 
) 
RETURNS varchar(255) CHARSET latin1 
LANGUAGE SQL 
NOT DETERMINISTIC 
CONTAINS SQL 
SQL SECURITY DEFINER 
COMMENT '' 
begin 
declare tempstring varchar(100); 
declare outstring varchar(100); 
declare book_types varchar(100); 
declare bin_position int; 
declare str_length int; 
declare checkit int; 
set tempstring = reverse(lpad(conv(indec,10,2),4,0)); 
set str_length = length(tempstring); 
set checkit = 0; 
set bin_position = 0; 
set book_types = ''; 
looper: while bin_position < str_length do 
     set bin_position = bin_position + 1; 
     set outstring = substr(tempstring,bin_position,1); 


     if outstring = 1 then 
      set book_types = concat(book_types,(select trim(type) from t where id = bin_position),','); 
     end if; 
end while; 

set outstring = book_types; 

return outstring; 
end // 
delimiter ; 

結果

+----+----------+---------------------------+ 
| id | username | book_type(id)    | 
+----+----------+---------------------------+ 
| 1 | John  | novel,     | 
| 2 | Jane  | fairy Tale,    | 
| 3 | Ali  | novel,fairy Tale,   | 
| 6 | Bruce | fairy Tale,bedtime,  | 
| 7 | Martha | novel,fairy Tale,bedtime, | 
+----+----------+---------------------------+ 
5 rows in set (0.00 sec) 

請注意UDF中的循環遍歷二進制字符串,並且1的位置與查找表中的ID相關; 我把它留給你來編碼錯誤和整理。

+0

從這個例子中,我需要像小說閱讀器一樣抓取片段(1,3,7)。你能解釋這將如何幫助我嗎? – r123

+0

您可以在select的where子句中使用find_in_set('novel',book_type(u.id)); –

+0

@ruby你看到我的最新評論嗎? –