【问题标题】:How to get column name in SQL如何在 SQL 中获取列名
【发布时间】:2014-05-23 05:40:26
【问题描述】:

我正在尝试从表中获取列名(IIS、SQL 服务器 PHP)。 我需要检查数据库中是否存在值,如果存在我需要获取列名。但我需要检查同一张表中的 3 个不同的列。

$sql = "SELECT bag_code, box_code, date_code 
        FROM packing 
        WHERE bag_code='$code_verification' OR box_code='$code_verification' 
        OR date_code='$code_verification'";

我对编写查询感到震惊。我进行了搜索,但没有找到任何解决方案。在这里,我想根据某些特定值显示列名

For Instance , My table is like.
id  | fruits   |vegetables    |softdrink
-----------------------
1   | apple    | Onion        | Pepsi
2   | mango    | Potato       | Coke    
3   | banana   | Bringal      | RedBull

如果我有一个值“芒果”,那么我应该将列名作为水果或

如果我有一个值“RedBull”,那么我应该将列名作为软饮料

【问题讨论】:

  • 基本方法是使用mysqli_num_rows()或PDO的rowCount()
  • 那我不明白你的问题。一列是一行。如果要检查“列”下是否存在记录,则使用if(mysqli_num_rows($query) > 0){...}或$numrows=mysqli_num_rows($query); if($numrows > 0){...}除此之外,您需要更清楚您的问题。
  • 请看我的问题
  • 您的数据库结构错误。
  • 啊好的,我现在明白了。然后,您可以使用 AS 关键字来使用并选择列作为别名。即:SELECT column_name AS alias_name 或 SELECT column1 AS alias1, column2 AS alias2 FROM table - 请参阅手册 dev.mysql.com/doc/refman/5.1/en/identifiers.html

标签: php sql sql-server-2005 iis-6


【解决方案1】:

重组你的表格

如果继续这种表结构,以后会很麻烦。

目前你有这个:

id  | fruits   |vegetables    |softdrink
----+----------+--------------+----------
1   | apple    | Onion        | Pepsi
2   | mango    | Potato       | Coke    
3   | banana   | Bringal      | RedBull

你可能想过: SELECT fruits FROM table 很简单吧?

这是错误的;

你必须这样做:

项目

id  | item_name| item_type_id |
----+----------+--------------+
1   | apple    | 1            |
2   | mango    | 1            | 
3   | banana   | 1            |
4   | Onion    | 2            |
5   | Potato   | 2            |
6   | Bringal  | 2            |
7   | Pepsi    | 3            |
8   | Coke     | 3            |
9   | RedBull  | 3            |

item_type

id  | item_type   | 
----+-------------+
1   | fruits      | 
2   | vegestables | 
3   | softdrinks  | 

SELECT * FROM table WHERE item_type_id = 1 /*selects all fruits*/

构建表格后。 这将是您问题的答案:

SELECT it.item_type FROM items i INNER JOIN USING(i.item_type_id = it.id) WHERE i.item_name LIKE '%mango%'

这将返回fruits。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多