如何在MySQL表上进行数据出现搜索

时间:2012-01-28 12:26:26

标签: mysql search lookup

我是MySQL和MySQL的新手。 PHP。 我有2个像这样的表,有超过数千行。

Table "Company A" 
id | Date       | Prize_1   | Prize_2   | Prize_3 | Prize_Consolation
1  | 2011-01-13 | "car"     | "ipad2"   | "bag"   | "mouse" 
2  | 2011-02-13 | "ps3"     | "iphone4" | "mouse" | "bag"

Table "Company B" 
id | Date       | Prize_1   | Prize_2   | Prize_3 | Prize_Consolation 
1  | 2011-01-18 | "tv"      | "iphone4" | "ipod"  | "bag" 
2  | 2011-02-13 | "iphone4" | "ipad"    | "bag"   | "mouse"

用户将随机发送查询以搜索关于奖励的历史信息。什么时候和哪家公司发行。

示例:我想在两个表格上搜索奖品" iphone4 "它应该返回如下结果:

Company   | Date       | Prize
Company A | 2011-02-13 | Prize_2
Company B | 2011-01-18 | Prize_2
Company B | 2011-02-13 | Prize_1

Total 3 prizes for "iphone4"

MySQL查询将实现此查找搜索?

1 个答案:

答案 0 :(得分:3)

这些实际上不应该是两个单独的表,而是一个带有公司标识列的表。

但是你的情况可以用一种黑客的方式解决:

SELECT
  'Company A' AS Company,
  Date, 
  CASE 
    WHEN Prize_1 = 'iphone4' THEN 'Prize_1'    
    WHEN Prize_2 = 'iphone4' THEN 'Prize_2'
    WHEN Prize_3 = 'iphone4' THEN 'Prize_3'
    WHEN Prize_Consolation = 'iphone4' THEN 'Prize_Consolation'
    ELSE NULL
  END AS Prize
FROM `Company A`
WHERE 
  Prize_1 = 'iphone4'
  OR Prize_2 = 'iphone4'
  OR Prize_3 = 'iphone4'
  OR Prize_Consolation = 'iphone4'
/* UNION performs the same query against both tables and combine the results */
UNION
SELECT 
  'Company B' AS Company,
  Date, 
  CASE 
    WHEN Prize_1 = 'iphone4' THEN 'Prize_1'    
    WHEN Prize_2 = 'iphone4' THEN 'Prize_2'
    WHEN Prize_3 = 'iphone4' THEN 'Prize_3'
    WHEN Prize_Consolation = 'iphone4' THEN 'Prize_Consolation'
    ELSE NULL
  END AS Prize

FROM Company B 哪里 Prize_1 ='iphone4' 或Prize_2 ='iphone4' 或者Prize_3 ='iphone4' 或Prize_Consolation ='iphone4'

此设计的表格布局更合适:

Table Prizes
---------------
id INT AUTO_INCREMENT,
Date DATETIME,
Company VARCHAR(256),
Prize_Type INT,
Prize_Item VARCHAR(256)

Table Prize_Types
---------------
Prize_Type INT AUTO_INCREMENT PRIMARY KEY,
Prize_Description VARCHAR(32)

奖品

1 | 2012-01-28 08:00:00 | 'Company A' | 3 | 'some prize'
2 | 2012-01-28 08:00:00 | 'Company A' | 2 | 'ipad'
3 | 2012-01-28 08:00:00 | 'Company A' | 1 | 'junky phone'
4 | 2012-01-28 08:00:00 | 'Company b' | 4 | 'iphone4'

Prize_Types

1 | 'Prize 1'
2 | 'Prize 2'
3 | 'Prize 3'
4 | 'Consolation Prize'

将其查询为:

SELECT
  Company,
  Date,
  Prize_Item,
  Prize_Description
FROM Prizes JOIN Prize_Types ON Prize_Types.Prize_Type = Prizes.Prize_Type
WHERE Prize_Item = 'iphone4'

事实上,您可能还希望将公司和奖品标准化为自己的表格,以及Prize_Types。