I have a SQL query in MYSQL:
For example
SELECT s.* FROM vplanning.cities as c1
INNER JOIN vplanning.cities as c2
ON (c1.id = c2.area_id)
INNER JOIN vplanning.storages as s
ON (s.city_id = c2.id OR s.city_id = c1.id)
WHERE c1.id = 109;
In doctrine I can write something like this (from my work code):
$query = $em->getRepository('VplanningPageBundle:Storage')
->createQueryBuilder('s')
->innerJoin('s.city', 'c1')
->innerJoin('c1.area', 'c2')
->innerJoin('s.storagestype', 'st')
->where('c2.id = :cityID')
->andWhere('st.typename = :storagesTypeName')
->andWhere('s.active = :active')
->setParameters(array(
'cityID' => $cityID,
'storagesTypeName' => $storagesTypeName,
'active' => 1
))
->orderBy('s.adress')
->getQuery();
As you can see, I show my relation in
->innerJoin('s.city', 'c1')
but I need also relation like
->innerJoin('s.city', 'c2')
with this condition:
ON (s.city_id = c2.id OR s.city_id = c1.id)
But it throws this error:
Error: 'c2' is already defined
c1 and c2 are the same entity and have a inner relation.
Try this:
$repository = $em->getRepository('VplanningPageBundle:Storage');
$qb = $repository->createQueryBuilder('storage');
//We can now use the expr()
$qb->join('storage.city', 'city', Join::WITH)
->join('city.area', 'area', Join::WITH, $qb->expr()->eq('area.id', ':cityID'))
->join('storage.storagestype', 'type', Join::WITH, $qb->expr()->eq('type.typename', ':storagesTypeName'))
->where('storage.active = :active')
->setParameters(array(
'cityID' => $cityID,
'storagesTypeName' => $storagesTypeName,
'active' => 1
))
->orderBy('storage.adress');
$query = $qb->getQuery();
Try smth like this
$qb = $this->getRepository('VplanningPageBundle:City')->createQueryBuilder('c');
$qb->leftJoin('c.area', 'a')
->join('c.storage', 's', Join::ON, $qb->expr()->orX($qb->expr()->eq('c.id', 's.id'), $qb->expr()->eq('a.id', 's.id')))
->innerJoin('s.storagestype', 'st')
->where('c.id = :cityID')
->andWhere('st.typename = :storagesTypeName')
->andWhere('s.active = :active')
->setParameters(array(
'cityID' => $cityID,
'storagesTypeName' => $storagesTypeName,
'active' => 1,
))
->orderBy('s.adress')
->getQuery()
;
The solution of the problem was very difficult as for me, I have to study it :)
This is a answer for my question from some forum board:
$qb = $em->getRepository('VplanningPageBundle:Storage')->createQueryBuilder('storage');
$query = $qb->join('storage.city', 'city1', Join::WITH)
->leftJoin('city1.area', 'area', Join::WITH, $qb->expr()->eq('area.id', ':cityID'))
->leftJoin('storage.city', 'city2', Join::WITH, $qb->expr()->eq('city2.id', ':cityID'))
->join('storage.storagestype', 'type', Join::WITH, $qb->expr()->eq('type.typename', ':storagesTypeName'))
->where('storage.active = :active')
->andWhere($qb->expr()->orX($qb->expr()->isNotNull('city2'), $qb->expr()->isNotNull('area')))
->setParameters(array(
'cityID' => $cityID,
'storagesTypeName' => $storagesTypeName,
'active' => 1
))
->orderBy('storage.adress')
->getQuery();
Related
Select tickets.id with calendar_date is null if last tickets.p_id(child row) calendar_date is null.
I want to convert this query in yii2 search model:
mysql query:
`SELECT b.ticket_id FROM (SELECT a.ticket_id FROM (
SELECT t.id AS ticket_id FROM tech_support.tickets t
WHERE t.tree_status_id = 2 AND t.p_id IS NULL) a
LEFT JOIN tech_support.tickets tt ON tt.p_id = a.ticket_id
WHERE tt.p_id IS NULL) b
LEFT JOIN tech_support.tickets ttt ON ttt.id = b.ticket_id WHERE
ttt.calendar_date IS NULL UNION ALL
SELECT b.maxid FROM (SELECT a.maxid, tt.calendar_date FROM (
SELECT MAX(t.id) AS maxid FROM tech_support.tickets t WHERE
t.tree_status_id = 2 GROUP BY t.p_id) a
LEFT JOIN tech_support.tickets tt ON tt.id = a.maxid) b
WHERE b.calendar_date IS NULL;`
yii2 code:
$subQuery = Tickets::find()
->select(new Expression('id as ticket_id'))
->where('tree_status_id = 2')
->andWhere('p_id is null')
->alias('a');
$subQuery->leftJoin('tickets', 'tickets.p_id = a.ticket_id')
->where('tickets.p_id is null')->all();
$query1 = (new \yii\db\Query())
->select(new Expression('id as ticket_id'))
->from($subQuery)
->where('p_id is null')
->alias('b');
$query1->leftJoin(['ttt' => 'tickets'], 'ttt.id =
b.ticket_id')
->where('ttt.calendar_date IS NULL');
$subQuery2 = Tickets::find()
->select(new Expression('MAX(tickets.id) as maxid'))
->where('tree_status_id = 2')
->groupBy(['p_id'])
->alias('a');
$subQuery2->leftJoin(['tt' => 'tickets'], 'tt.id = a.maxid')
->all();
$query2 = (new \yii\db\Query())
->select('maxid')
->from($subQuery2);
$query1->union($query2);
$query1->where('calendar_date is null');
Error Info:
Integrity constraint violation – yii\db\IntegrityException
Please help me.
Result:
//----------------query1------------------------------
$query = (new \yii\db\Query())
->select('t.id as ticket_id')
->from(['t' => 'tickets'])
->where('t.tree_status_id = 2')
->andWhere('t.p_id is null');
$subQuery = (new \yii\db\Query())
->select('a.ticket_id')
->from(['a' => $query]);
$subQuery->leftJoin(['tt' => 'tickets'], 'tt.p_id = a.ticket_id')
->where('tt.p_id is null');
$query1 = (new \yii\db\Query())
->select('b.ticket_id')
->from(['b' => $subQuery]);
$query1->leftJoin(['ttt' => 'tickets'], 'ttt.id = b.ticket_id')
->where('ttt.calendar_date IS NULL');
//----------------query2------------------------------
$subQuery2 = (new \yii\db\Query())
->select('MAX(t.id) as maxid')
->from(['t' => 'tickets'])
->where('t.tree_status_id = 2')
->groupBy(['t.p_id']);
$query2 = (new \yii\db\Query())
->select(['a.maxid', 'tt.calendar_date'])
->from(['a' => $subQuery2]);
$query2->leftJoin(['tt' => 'tickets'], 'tt.id = a.maxid');
$query3 = (new \yii\db\Query())
->select('b.maxid')
->from(['b' => $query2]);
$query3->leftJoin(['ttt' => 'tickets'], 'ttt.id = b.maxid')
->where('ttt.calendar_date IS NULL');
//----------------union queries------------------------------
$unionQuery = (new \yii\db\Query())
->from([$query1->union($query3, true)]);
I need to get ordered list by three fields.
$sql = "
SELECT
SQL_CALC_FOUND_ROWS $wpdb->posts.ID
FROM
$wpdb->posts
INNER JOIN
$wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )
INNER JOIN
$wpdb->postmeta AS mt1 ON ( $wpdb->posts.ID = mt1.post_id )
WHERE
1=1
AND
(
( mt1.meta_key = 'pub_series' AND mt1.meta_value = 'Book' )
OR ( mt1.meta_key = 'pub_series' AND mt1.meta_value = 'Book chapter' )
OR ( mt1.meta_key = 'pub_series' AND mt1.meta_value = 'Journal Article' )
)
/*AND
(
mt3.meta_key = 'forthcoming'
)*/
AND
$wpdb->postmeta.meta_key = 'pub_year'
AND
$wpdb->posts.post_type = 'publication'
AND
$wpdb->posts.post_status = 'publish'
GROUP BY
$wpdb->posts.ID
ORDER BY
/*FIELD(mt3.meta_key, 'forthcoming') DESC,
FIELD(mt3.meta_value, 'null') DESC,*/
//FIELD($wpdb->postmeta.meta_value,1),
$wpdb->postmeta.meta_value DESC,
$wpdb->posts.post_date DESC
";
$total = count($wpdb->get_results($sql));
$offset = ( $paged * $posts_per_page ) - $posts_per_page;
$results = $wpdb->get_results( $sql . "
LIMIT
$offset, $posts_per_page" );
This is query ordered list by two fields: [custom_field] pub_year (possible values 2018, 2017...) and [delautl wp post date field] post_date. It is ok.
But now I need to show items with [custom_field] forthcoming = 1. Problem that there three states if this field:
- items with forthcoming = 1
- items with forthcoming = 0
- and items where custom field forthcoming not exist
I need to get ordered list with firts items forthcoming = 1 and other should be ordered by pub_year and date. How I can do this. Tell me if you need some more info. Thanks a lot.
I was get needed ordered list with adding for all posts meta key forthcoming = 0 with update meta method. So all fields have this field.
Next I was used wp_query meta_query args:
$pub_series = 'Book,Book chapter,Journal Article';
$search_args = array();
if (!empty($pub_series)) {
$pub_series_arr = explode(",", $pub_series);
if (!empty($pub_series_arr)) {
$search_args_add = array(
'relation' => 'OR'
);
foreach ($pub_series_arr as $pub_series_el) {
$adv_search_query_el = trim($pub_series_el);
if (!empty($adv_search_query_el)) {
$search_args_add[] = array(
'key' => 'pub_series',
'value' => $adv_search_query_el,
'compare' => '='
);
}
}
$search_args['meta_query'][] = $search_args_add;
}
}
$search_args['meta_query'][] = array(
'relation' => 'OR',
'forthcoming_clause' => array(
'key' => 'forthcoming',
'value' => '1'
),
'forthcoming_clause0' => array(
'key' => 'forthcoming',
'value' => '0'
)
);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'publication',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => array(
'forthcoming_clause' => 'DESC',
'meta_value' => 'DESC',
'date' => 'DESC'
),
'meta_key' => 'pub_year',
'paged' => $paged
);
$args = array_merge($args, $search_args);
$posts = new WP_Query( $args );
if ( $posts->have_posts() ) : ...
I'm strugling with this query within prestashop , i know it could be easily fixed by changing to sa.available_for_order but this way it breaks the logic of other core files ,
is there any other way around to fix this without renaming available_for_order to sa.available_for_order ,
SELECT
a.`id_product`,
b.`name` AS `name`,
`reference`,
a.`price` AS `price`,
sa.`active` AS `active`,
`newfield`,
shop.`name` AS `shopname`,
a.`id_shop_default`,
image_shop.`id_image` AS `id_image`,
cl.`name` AS `name_category`,
sa.`price`,
0 AS `price_final`,
a.`is_virtual`,
pd.`nb_downloadable`,
sav.`quantity` AS `sav_quantity`,
sa.`active`,
IF(sav.`quantity` <= 0, 1, 0) AS `badge_danger`,
sa.`available_for_order` AS `available_for_order`
FROM
`ps_product` a
LEFT JOIN
`ps_product_lang` b
ON
(
b.`id_product` = a.`id_product` AND b.`id_lang` = 1 AND b.`id_shop` = 1
)
LEFT JOIN
`ps_stock_available` sav
ON
(
sav.`id_product` = a.`id_product` AND sav.`id_product_attribute` = 0 AND sav.id_shop = 1 AND sav.id_shop_group = 0
)
JOIN
`ps_product_shop` sa
ON
(
a.`id_product` = sa.`id_product` AND sa.id_shop = a.id_shop_default
)
LEFT JOIN
`ps_category_lang` cl
ON
(
sa.`id_category_default` = cl.`id_category` AND b.`id_lang` = cl.`id_lang` AND cl.id_shop = a.id_shop_default
)
LEFT JOIN
`ps_shop` shop
ON
(
shop.id_shop = a.id_shop_default
)
LEFT JOIN
`ps_image_shop` image_shop
ON
(
image_shop.`id_product` = a.`id_product` AND image_shop.`cover` = 1 AND image_shop.id_shop = a.id_shop_default
)
LEFT JOIN
`ps_image` i
ON
(
i.`id_image` = image_shop.`id_image`
)
LEFT JOIN
`ps_product_download` pd
ON
(pd.`id_product` = a.`id_product`)
WHERE
1 AND `available_for_order` = 1
ORDER BY
a.`id_product` ASC
LIMIT 0, 50
PRESTASHOP
public function __construct()
{
parent::__construct();
$this->_select .= ',sa.`available_for_order` AS `available_for_order`, ';
$this->fields_list['sa!available_for_order'] = array(
'title' => $this->l('Available for order'),
'width' => 90,
'active' => 'available_for_order',
'filter_key' => 'sa!available_for_order',
'type' => 'bool',
'align' => 'center',
'orderby' => false
);
}
Modify your fields list to use having filter.
$this->fields_list['available_for_order'] = array(
'title' => $this->l('Available for order'),
'width' => 90,
'active' => 'available_for_order',
'filter_key' => 'available_for_order',
'havingFilter' => true,
'type' => 'bool',
'align' => 'center',
'orderby' => false
);
This will use HAVING instead of WHERE in query.
WHERE clause does not work on column aliases but HAVING does.
The column available_for_order must be in more than one of the tables. Just qualify the column name, as you do in the select:
WHERE 1 AND sa.available_for_order = 1
------------^
Updated SQL: Environment is MySQL 5.5. The SQL is being generated through a phpBB abstraction layer but when I see the SQL it looks valid.
SELECT f.*, t.*, p.*, u.*, tt.mark_time AS topic_mark_time, ft.mark_time AS forum_mark_time
FROM (phpbb_posts p CROSS JOIN phpbb_users u CROSS JOIN phpbb_topics t) LEFT JOIN
phpbb_forums f ON (t.forum_id = f.forum_id) LEFT JOIN phpbb_topics_track tt ON
(t.topic_id = tt.topic_id AND tt.user_id = 2) LEFT JOIN phpbb_forums_track ft ON
(f.forum_id = ft.forum_id AND ft.user_id = 2) WHERE p.topic_id = t.topic_id AND
p.poster_id = u.user_id AND p.post_time > 1380495918 AND p.forum_id IN (7, 6, 5, 3, 4, 2, 1)
AND p.post_approved = 1 ORDER BY t.topic_last_post_time DESC, p.post_time LIMIT
18446744073709551615
Error is:
Unknown column 't.topic_id' in 'on clause' [1054]
All column names exist. All tables exist. All aliases exist.
Here's the associated code:
$sql_array = array(
'SELECT' => 'f.*, t.*, p.*, u.*, tt.mark_time AS topic_mark_time, ft.mark_time AS forum_mark_time',
'FROM' => array(
POSTS_TABLE => 'p',
USERS_TABLE => 'u',
TOPICS_TABLE => 't'),
'WHERE' => "$topics_posts_join_sql
AND p.poster_id = u.user_id
$date_limit_sql
$fetched_forums_str
$new_topics_sql
$remove_mine_sql
$filter_foes_sql
AND p.post_approved = 1",
'ORDER_BY' => $order_by_sql
);
$sql_array['LEFT_JOIN'] = array(
array(
'FROM' => array(FORUMS_TABLE => 'f'),
'ON' => 't.forum_id = f.forum_id'
),
array(
'FROM' => array(TOPICS_TRACK_TABLE => 'tt', FORUMS_TRACK_TABLE => 'ft'),
'ON' => "t.topic_id = tt.topic_id AND tt.user_id = $user_id"
),
array(
'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
'ON' => "f.forum_id = ft.forum_id AND ft.user_id = $user_id"
)
);
$sql = $db->sql_build_query('SELECT', $sql_array);
t.topic_id = TOPICS_TRACK_TABLE.topic_i
Is wrong. Make sure it uses the correct alias tt
I have the following query that works, but after talking to the client I realized I need left joins to get the desired results and I don't know how to do it.
This is my query:
$query = $this->AssetStatusAudits->find('all', [
'contain' => [
'AssetStatus',
'Users',
'Assets' => function ($q) {
return $q->contain([
'Employees',
'Sites'
]);
}
],
'conditions' => [
'AssetStatusAudits.created >' => $from,
'AssetStatusAudits.created <' => $to
]
]);
$query->select([
'createdDate' => 'date(AssetStatusAudits.created)',
'assetStatus' => 'AssetStatus.desc_en',
'firstName' => 'Users.first_name',
'lastName' => 'Users.last_name',
'count' => $query->func()
->count('*')
])
->group('date(AssetStatusAudits.created)', 'assetStatus.desc_en', 'users.last_name')
->order('Users.last_name', 'Users.created');
The above query generates this in cake:
SELECT date(AssetStatusAudits.created) AS `createdDate`,
AssetStatus.desc_en AS `assetStatus`,
Users.first_name AS `firstName`,
Users.last_name AS `lastName`,
(COUNT(*)) AS `count`
FROM asset_status_audits AssetStatusAudits
INNER JOIN asset_status AssetStatus ON AssetStatus.id = (AssetStatusAudits.asset_status_id)
INNER JOIN users Users ON Users.id = (AssetStatusAudits.user_id)
INNER JOIN assets Assets ON Assets.id = (AssetStatusAudits.asset_id)
LEFT JOIN employees Employees ON Employees.id = (Assets.employee_id)
INNER JOIN sites Sites ON Sites.id = (Assets.site_id)
WHERE (AssetStatusAudits.created > date('2016-01-13') AND AssetStatusAudits.created < date('2016-05-03'))
GROUP BY date(AssetStatusAudits.created)
ORDER BY Users.last_name
But this is the query that I need to add to cakePHP and I don't know how to do it:
SELECT
date(asset_tracking.asset_status_audits.created) as 'Date',
asset_tracking.asset_status.desc_en as 'Status',
asset_tracking.users.first_name as 'First Name' ,
asset_tracking.users.last_name as 'Last Name',
count(*)
FROM asset_tracking.asset_status_audits
LEFT OUTER JOIN asset_tracking.assets ON asset_tracking.asset_status_audits.asset_id = asset_tracking.assets.id
LEFT OUTER JOIN asset_tracking.asset_status ON asset_tracking.asset_status_audits.asset_status_id = asset_tracking.asset_status.id
LEFT OUTER JOIN asset_tracking.users ON asset_tracking.asset_status_audits.user_id = asset_tracking.users.id
LEFT OUTER JOIN asset_tracking.employees ON asset_tracking.assets.employee_id = asset_tracking.employees.id
LEFT OUTER JOIN asset_tracking.sites ON asset_tracking.assets.site_id = asset_tracking.sites.id
WHERE asset_tracking.asset_status_audits.created between date('2016-01-13') and date('2016-05-19')
group by
date(asset_tracking.asset_status_audits.created) ,
asset_tracking.asset_status.desc_en,
asset_tracking.users.last_name
ORDER BY asset_tracking.users.last_name, asset_tracking.users.created;