【问题标题】:MySQL query row based on current rowMySQL 根据当前行查询行
【发布时间】:2016-01-11 10:37:14
【问题描述】:

上面是我的桌子。现在我想要实现的是查询类型为“main”的查询,包括所有“sub”,其中 parent 等于当前行的 id。我怎样才能做到这一点?任何帮助将不胜感激!

以下是我当前的代码:

$conn = new PDO("mysql:host=$host;dbname=$db_name",$user,$pass) or die("DB Connection failed!!");
$stmt = $conn->prepare('SELECT * FROM tbl_categories WHERE type="main"');
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
//first loop i should get Electronics, Laptops, Mobile Phones
//second loop i should get Fashion, Men, Women
}

我不想在 while 循环中执行另一个查询。

【问题讨论】:

  • 在 sql 中('普通' sql,即不是游标等)是基于集合的。因此,没有“当前行”。说明您需要什么,以及您尝试了什么。
  • 当前行是谁?您是指类型为“main”的行吗?向我们展示您期望的输出
  • OP 已更新.. @AlexandruSeverin
  • OP 更新了@HoneyBadger

标签: mysql sql pdo


【解决方案1】:

您的问题不是很清楚,但这是您可以在数据库级别做到的方式。

select * from tbl_categories 
where parent in
(
    select id from tbl_categories
    where type='main'
)

如果您只想获取Fashion 的详细信息,请使用此

select * from tbl_categories 
where parent in
(
    select id from tbl_categories
    where type='main'
    and Category='Fashion'
)

SQL Fiddle 示例

http://sqlfiddle.com/#!9/ea58e/2

【讨论】:

    【解决方案2】:

    我认为您的数据中有错误:为什么fashion = 1parent 是?我认为是null,与Electronics 相同。考虑到这一点,试试这个:

    DECLARE @T TABLE (id INT, category VARCHAR(255), Type VARCHAR(50), Parent int)
    ;
    
    INSERT @T
            ( id, category, Type, Parent )
    VALUES  ( 1, 'Electronics', 'Main', NULL)
    ,       ( 2, 'Laptops', 'Sub', 1)
    ,       ( 3, 'Mobile phones', 'Sub', 1)
    ,       ( 4, 'Fashion', 'Main', NULL)
    ,       ( 5, 'Men', 'Sub', 4)
    ,       ( 6, 'Women', 'Sub', 4)
    
    SELECT      T2.*
    FROM        @T AS T
    INNER JOIN  @T AS T2
            ON  T2.Parent = T.id
    WHERE       T.Type = 'Main'
    

    结果:

    id  category    Type    Parent
    2   Laptops Sub 1
    3   Mobile phones   Sub 1
    5   Men Sub 4
    6   Women   Sub 4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      相关资源
      最近更新 更多