How to write this query in codeigniter
SELECT U.username,U.user_id
FROM storylikes S, user U
WHERE U.user_id=S.user_id_fk AND S.user_id_fk='$id'
try this :
$this->db->select('u.username, u.user_id');
db->where('u. user_id = s.user_id_fk');
$this->db->where('s.user_id_fk = '.$id);
$query = $this->db->get('storylikes s, user u');
use $your_variable = $query->result(); for the result
you should use joins instead of this query
$this->db->select('username,user_id');
$this->db->from('user');
$this->db->join('storylike','storylike.user_id_fk = user.user_id');
$this->db->where('storylike.user_id','$id');
as long as the db helper is loaded... You dont need to do anything special
$query = $this->db->query('SELECT U.username,U.user_id FROM storylikes S, user U WHERE U.user_id=S.user_id_fk AND S.user_id_fk=$id);
Using a cartesian (cross join) by doing FROM with 2 tables can cause some unruly results if not used 'correctly'
I suggest that if you are trying to just join tables together your SQL should be
SELECT U.username,U.user_id
FROM storylikes S, user U
INNER JOIN user U ON S.user_id = U.user_id_fk
WHERE S.user_id_fk=$id
CI querybuilder for this would be:
$query = $this->db->select('U.username,U.user_id')
->join('user U', 'S.user_id = U.user_id_fk', 'inner')
->where('S.user_id', $id)
->get('user U');
Using the correct join for the correct requirements is key;
INNER JOIN to ensure both FROM and the JOIN table match 1 for 1...
LEFT JOIN if you want to ensure you have all data from your FROM table and any without results in the JOIN table show up as NULL
RIGHT JOIN (opposite of left), to grab all data from the JOIN table and only matching data from the FROM table.
CROSS (CARTESIAN) JOIN when you want to ... frankly... mash the data together... A CROSS JOIN will also function like an INNER JOIN when you stipulate criteria in the WHERE statement (like you did) but still, use the correct JOIN for the correct usage-case.
There are other available joins but those are the basics.
Related
I am stuck in 1 left join query in which I want to check multiple columns in on statement.
By default in the database, some column is null which I want to check in the on statement.
Now the issue is when I run a query using the OR operator it only runs the 1st condition and the rest are skipped.
If I use AND operator it throws an error.
So is there any way to get data from multiple conditions?
Here is my query:
$data = "SELECT
b.book_name, b.book_id,
b.cats_id, b.cats_id1,
b.cats_id2, b.cats_id3,
b.cats_id4, b.cats_id5,
b.cats_id6,
b.book_rating,
b.book_author,
b.book_stock,
b.book_publisher,
b.book_front_img,
b.book_status,
p.publisher_id,
p.publisher_name,
a.author_id,
a.author_name,
cat.cats_id,
cat.cats_name,
cat.cats_status
FROM
`books` AS b
LEFT JOIN `publisher` AS p
ON b.book_publisher = p.publisher_id
LEFT JOIN `author` AS a
ON b.book_author = a.author_id
LEFT JOIN categorys As cat
ON b.cats_id = cat.cats_id
OR b.cats_id1 = cat.cats_id
OR b.cats_id2 = cat.cats_id
OR b.cats_id3 = cat.cats_id
OR b.cats_id4 = cat.cats_id
OR b.cats_id5 = cat.cats_id
OR b.cats_id6 = cat.cats_id
GROUP BY
b.book_name
HAVING
cat.cats_name = '$search_data'
AND b.book_status = 1
ORDER BY
$sorting
LIMIT $offset, $page_limit"
You probably don't have more than one author displayed for your multi-author books either. You are misusing MySQL's notorious nonstandard extension to GROUP BY.
To troubleshoot this kind of query, disable that extension with SET sql_mode = CONCAT_WS(',',##sql_mode, 'ONLY_FULL_GROUP_BY'), then try your query again. You'll need more terms in your GROUP BY clause.
It looks like each books row has multiple category id columns. And it looks like you want to display information from your categorys table for each of them.
Use GROUP BY b.book_id, p.publisher_id, a.author_id, cats.cats_id to prevent MySQL's bizarro handling of GROUP BY from concealing your data.
I must add this: your multiple books.cats_id columns are not the SQLish way to handle your many-to-many relationship between books and categories. In the parlance of our trade, your books table is denormalized.
What you want is a new table called books_categorys with two columns, book_id and cats_id. It's called a join table. When a row is present in that table, it means a particular book is in a particular category. It's the SQLish way of handling a setup where each book can be in zero or more categorys. Here's an explanation. MySQL join many to many single row
Then you remove all the cats_id columns from books, and retrieve the categories like this.
Then you do something like this SELECT to get the categories.
SELECT books.id, books.name,
categorys.cats_id, categorys.cats_name, categorys.cats_status
FROM books
JOIN books_categorys ON books.book_id = books_categorys.book_id
JOIN categorys ON books_categorys.cats_id = categorys.cats_id
``
I have two tables named DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1 and DE1_0_2008_BENEFICIARY_SUMMARY_FILE_SAMPLE_1 in the same database.
I have to perform a query on DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1 and then perform the LEFT JOIN of this queried result with `DE1_0_2008_BENEFICIARY_SUMMARY_FILE_SAMPLE_1'. The query alone results in 1178 rows which is fine. But I am not able to do the LEFT JOIN. I used this SQL query:
SELECT *
FROM `DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1`
LEFT JOIN DE1_0_2008_BENEFICIARY_SUMMARY_FILE_SAMPLE_1
ON DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1.DESYNPUF_ID = DE1_0_2008_BENEFICIARY_SUMMARY_FILE_SAMPLE_1.DESYNPUF_ID
WHERE DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1.ICD9_DGNS_CD_1 = 7243 OR DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1.ICD9_DGNS_CD_2 = 7243 OR DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1.ICD9_DGNS_CD_3 = 7243 OR ICD9_DGNS_CD_4 = 7243
This query is technically fine.
Note that it can be rewritten more elegantly as follows, but really you need to take a closer look at both partitioning and, crucially, normalisation...
SELECT *
FROM DE1_0_2008_TO_2010_OUTPATIENT_CLAIMS_SAMPLE_1 o
LEFT
JOIN DE1_0_2008_BENEFICIARY_SUMMARY_FILE_SAMPLE_1 b
ON o.DESYNPUF_ID = b.DESYNPUF_ID
WHERE 7243 IN(o.ICD9_DGNS_CD_1,o.ICD9_DGNS_CD_2,o.ICD9_DGNS_CD_3,o.ICD9_DGNS_CD_4);
Can you use Doctrine QueryBuilder to INNER JOIN a temporary table from a full SELECT statement that includes a GROUP BY?
The ultimate goal is to select the best version of a record. I have a viewVersion table that has multiple versions with the same viewId value but different timeMod. I want to find the version with the latest timeMod (and do a lot of other complex joins and filters on the query).
Initially people assume you can do a GROUP BY viewId and then ORDER BY timeMod, but ORDER BY has no effect on GROUP BY, and MySQL will return random results. There are a ton of answers out there (e.g. here) that explain the problem with using GROUP and offer a solution, but I am having trouble interpreting the Doctrine docs to find a way to implement the SQL with Doctrine QueryBuilder (if it's even possible). Why don't I just use DQL? I may have to, but I have a lot of dynamic filters and joins that are much easier to do with QueryBuilder, so I wanted to see if that's possible.
Sample MySQL to Reproduce in Doctrine QueryBuilder
SELECT vv.*
FROM view_version vv
#inner join only returns where the result sets overlap, i.e. one record
INNER JOIN (
SELECT MAX(timeMod) maxTimeMod, viewId
FROM view_version
GROUP BY viewId
) version ON version.viewId = vv.viewId AND vv.timeMod = version.maxTimeMod
#join other tables for filter, etc
INNER JOIN view v ON v.id = vv.viewId
INNER JOIN content_type c ON c.id = v.contentTypeId
WHERE vv.siteId=1
AND v.contentTypeId IN (2)
ORDER BY vv.title ASC;
Theoretical Solution via Query Builder (not working)
I am thinking that the JOIN needs to inject a DQL statement, e.g.
$em = $this->getDoctrine()->getManager();
$viewVersionRepo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion');
$queryMax = $viewVersionRepo->createQueryBuilder()
->addSelect('MAX(timeMod) AS timeModMax')
->addSelect('viewId')
->groupBy('viewId');
$queryBuilder = $viewVersionRepo->createQueryBuilder('vv')
// I tried putting the query in a parenthesis, to no avail
->join('('.$queryMax->getDQL().')', 'version', 'WITH', 'vv.viewId = version.viewId AND vv.timeMod = version.timeModMax')
// Join other Entities
->join('e.view', 'view')
->addSelect('view')
->join('view.contentType', 'contentType')
->addSelect('contentType')
// Perform random filters
->andWhere('vv.siteId = :siteId')->setParameter('siteId', 1)
->andWhere('view.contentTypeId IN(:contentTypeId)')->setParameter('contentTypeId', $contentTypeIds)
->addOrderBy('e.title', 'ASC');
$query = $queryBuilder->getQuery();
$results = $query->getResult();
My code (which may not match the above example perfectly) outputs:
SELECT e, view, contentType
FROM Gutensite\CmsBundle\Entity\View\ViewVersion e
INNER JOIN (
SELECT MAX(v.timeMod) AS timeModMax, v.viewId
FROM Gutensite\CmsBundle\Entity\View\ViewVersion v
GROUP BY v.viewId
) version WITH vv.viewId = version.viewId AND vv.timeMod = version.timeModMax
INNER JOIN e.view view
INNER JOIN view.contentType contentType
WHERE e.siteId = :siteId
AND view.contentTypeId IN (:contentTypeId)
ORDER BY e.title ASC
This Answer seems to indicate that it's possible in other contexts like IN statements, but when I try the above method in the JOIN, I get the error:
[Semantical Error] line 0, col 90 near '(SELECT MAX(v.timeMod)': Error: Class '(' is not defined.
A big thanks to #AdrienCarniero for his alternative query structure for sorting the highest version with a simple JOIN where the entity's timeMod is less than the joined table timeMod.
Alternative Query
SELECT view_version.*
FROM view_version
#inner join to get the best version
LEFT JOIN view_version AS best_version ON best_version.viewId = view_version.viewId AND best_version.timeMod > view_version.timeMod
#join other tables for filter, etc
INNER JOIN view ON view.id = view_version.viewId
INNER JOIN content_type ON content_type.id = view.contentTypeId
WHERE view_version.siteId=1
# LIMIT Best Version
AND best_version.timeMod IS NULL
AND view.contentTypeId IN (2)
ORDER BY view_version.title ASC;
Using Doctrine QueryBuilder
$em = $this->getDoctrine()->getManager();
$viewVersionRepo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion');
$queryBuilder = $viewVersionRepo->createQueryBuilder('vv')
// Join Best Version
->leftJoin('GutensiteCmsBundle:View\ViewVersion', 'bestVersion', 'WITH', 'bestVersion.viewId = e.viewId AND bestVersion.timeMod > e.timeMod')
// Join other Entities
->join('e.view', 'view')
->addSelect('view')
->join('view.contentType', 'contentType')
->addSelect('contentType')
// Perform random filters
->andWhere('vv.siteId = :siteId')->setParameter('siteId', 1)
// LIMIT Joined Best Version
->andWhere('bestVersion.timeMod IS NULL')
->andWhere('view.contentTypeId IN(:contentTypeId)')->setParameter('contentTypeId', $contentTypeIds)
->addOrderBy('e.title', 'ASC');
$query = $queryBuilder->getQuery();
$results = $query->getResult();
In terms of performance, it really depends on the dataset. See this discussion for details.
TIP: The table should include indexes on both these values (viewId and timeMod) to speed up results. I don't know if it would also benefit from a single index on both fields.
A native SQL query using the original JOIN method may be better in some cases, but compiling the query over an extended range of code that dynamically creates it, and getting the mappings correct is a pain. So this is at least an alternative solution that I hope helps others.
Is it possible to write this sql query without alias? I am using a PHP script that doesn't covers alias so I have problem with that.
If this is possible please provide me with some help
This is the code:
SELECT
time1.Time, time2.Time, time1.Signal, v.name, v.lastname, k.vehicle, time1.Reg
FROM
data time1
INNER JOIN data time2
ON time1.id != time2.id
AND time1.serial= time2.serial
INNER JOIN drivers v
ON time1.FK_ID_driver=v.ID_driver
INNER JOIN vehicles k
ON time1.Reg=k.Reg
WHERE
TIMEDIFF(time2.Time, time1.Time) BETWEEN '00:15:00' AND '00:30:00';
You can't easily achieve what you want, since you are joining the same table twice, and SQL needs an alias to disambiguate them.
You could, however, create a view for table data, and use the view instead of the table name in one of the data joins.
Example:
select data.time,
vData.time,
data.Signal,
drivers.name,
drivers.lastname,
vehicles.vehicle,
data.Reg
from data
inner join vData on data.id != vData.id and data.serial = vData.serial
inner join drivers on data.FK_ID_driver = drivers.ID_driver
inner join vehicles on data.Reg = vehicles.Reg
where TIMEDIFF(vData.time, data.time) between '00:15:00' and '00:30:00';
I am currently running this SQL
SELECT jm_recipe.name, jm_recipe.slug
FROM jm_recipe
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"
This returns the desired results except that I also need to return the name of the category that the recipe I am looking for is in, to do this I tried to add the field in to my SELECT statement and also add the table into the FROM clause,
SELECT jm_recipe.name, jm_recipe.slug, jm_category_name
FROM jm_recipe, jm_category
LEFT JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
WHERE jm_category_recipe.category_id = $cat"
However this just returns no results, what am i doing wrong?
You need to join both tables:
SELECT jm_recipe.name, jm_recipe.slug, jm.category_name
FROM jm_recipe
INNER JOIN jm_category_recipe ON jm_category_recipe.recipe_id = jm_recipe.id
INNER JOIN jm_category ON jm_recipe.recipe_id = jm_category.recipe_id
WHERE jm_category_recipe.category_id = $cat
I've changed the joins to inner joins as well. You might want to make them both LEFT joins if you have NULLs and want them in the result.
Also, you're vulnerable to SQL Injection by simply copying over $cat.
Here's some PHP specific info for you (I'm assuming you're using PHP.)