I have two tables:
product:
id
image:
id
imageable_type
imageable_id
I am trying to execute a query to the effect of:
SELECT *
FROM product p
INNER JOIN image i
ON i.imageable_id = p.id
AND i.imageable_type = "product" # <--this
But due to the constraints of my application framework, I must append a field name to the alias p., so I am looking for something to the effect of:
AND i.imageable_type = p.TABLE_NAME # <--this
where TABLE_NAME is some built in "universal special field" so-to-speak that references name of the parent table. Is there such as feature in MySQL or other SQL db's?
Would your framework accept this?
SELECT *
FROM product p
INNER JOIN image i
ON i.imageable_id = p.id
WHERE i.imageable_type = "product"
Related
I have a few tables:
resources (which contains all the posts)
pid | usrnm | title | link | content | stitle | sdesc | at | likes
tags (which contains all the tags and an ID)
id | slug
retags (which connects the resource and it's tags)
pid | tid
I'm trying to make a search engine with which you can search by multiple tags, a search value and order the results by newest or most liked.
The SQL I use for searching by tags is:
SELECT
resources.pid, resources.title
FROM resources
INNER JOIN retags ON resources.pid = retags.pid
INNER JOIN tags ON retags.tid = tags.id
GROUP BY resources.pid
HAVING
SUM(tags.slug = 'tag-z')
AND
SUM(tags.slug = 'tag-y')
How can I apply the SQL for the search value WHERE title LIKE '%bla%' and order ORDER BY at DESC to this tag search SQL?
I tried select from select but kept gettings errors like "Duplicate column pid", "Column 'pid' in field list is ambiguous" etc
Can someone help me with this SQL? Thanks
I've tried everything in StackOverflow like using an alias for column name on oneSELECT pid as pid_ ... and even on both selects but I still kept getting the same duplicate column error.
EDIT: The SQL I've been getting errors from:
SELECT * FROM
(SELECT * FROM resources
INNER JOIN retags ON resources.pid = retags.pid
INNER JOIN tags ON retags.tid = tags.id
GROUP BY resources.pid
HAVING
SUM(tags.slug = 'A2') AND
SUM(tags.slug = 'AS')
) AS tsr WHERE tsr.title LIKE '%bla%' ORDER BY tsr.`at` DESC
This is just one of them, I've tried a lot of different types from other posts and different errors I get from them.
The WHERE clause goes before the GROUP BY:
SELECT rs.pid, rs.title
FROM resources rs JOIN
retags rt
ON rs.pid = rt.pid JOIN
tags t
ON rt.tid = t.id
WHERE rs.title LIKE '%bla%'
GROUP BY rs.pid
HAVING SUM(t.slug = 'tag-z') AND
SUM(t.slug = 'tag-y')
ORDER BY MAX(rs.at);
Strictly speaking, the MAX() is not needed in the ORDER BY assuming that pid uniquely identifies each row in resources.
My guess is that at is in multiple rows, so you need to qualify the reference with the table it comes from. Note that I introduced table aliases so the query is easier to write and to read.
I am having some trouble with my sql statement.
Here is a picture of the relevant tables:
A product can be in multiple categories.
A single product can have multiple varietycategories (ie: size, color, etc)
a varietycategory can have multiple varietycategoryoptions (ie: small, medium, large)
the table searchcriteria.criterianame loosly relates to varietycategory.category
the table searchcriteriaoption.criteriaoption loosely relates to varietycategoryoption.descriptor.
I get the searchcriteria.criterianame and use that string as the value we want to match with varietycategory.category and we also have to get the various searchcriteriaoption.criteriaoption strings (for that searchcriteria.criterianame) and match that against varietycategoryoption.descriptor for that varietycategory.category.
Here is the sql:
SELECT DISTINCT categories.*, product.*
FROM (categories, product, product_category)
LEFT JOIN varietycategory ON varietycategory.productid = product.id
LEFT JOIN varietycategoryoption ON varietycategoryoption.varietycategoryid = varietycategory.id
WHERE product_category.categoryid=4
AND product.id=product_category.productid
AND categories.category_id=product_category.categoryid
AND (
(varietycategory.category = 'color' AND (varietycategoryoption.descriptor='red' OR varietycategoryoption.descriptor='blue'))
OR
(varietycategory.category = 'size' AND (varietycategoryoption.descriptor = 'small' OR varietycategoryoption.descriptor='medium'))
)
but I get an error:
Unknown column 'varietycategory.id' in 'on clause'
I have tried to figure out what I am doing wrong. I tried simplifying the query a bit (just to try and determine what part of the sql query was causing the problem) to only match the searchcriteria.category string with the varietycategory.category and the query returns the data set correctly.
Here is the working query (this query is simplified and insufficient):
SELECT DISTINCT categories.*, product.*
FROM (categories, product, product_category)
LEFT JOIN varietycategory ON varietycategory.productid = product.id
WHERE product_category.categoryid=4
AND product.id=product_category.productid
AND categories.category_id=product_category.categoryid
AND (varietycategory.category = 'color' OR varietycategory.category = 'size' OR varietycategory.category='shape');
But I also need to be able to match against the varietycategoryoptions as well.
Just to avoid confusion, I am only using searchcriteria to get the field category and use it as a string to match against the varietycategory.category
and I am only using searchcriteriaoption to get the field criteriaoption and use it as a string to match against varietycategoryoption.descriptor
Does anyone know what I am doing wrong with my 1st query?
Please do help as SQL is not expertise.
Thank you!
The error is at:
OR
(varietycategory.category = 'size' (varietycategoryoption.desciptor = 'small' OR varietycategoryoption.descriptor='medium'))
^
|
An operator (AND, OR) is missing here
This has nothing to do with the join syntax, by the way.
Do not mix implicit and explicit joins. Your query should look like:
SELECT DISTINCT c.*, p.*
FROM product_category pc join
categories c
on c.category_id = pc.categoryid join
product p
on p.id = pc.productid join
varietycategory vc
ON vc.productid = p.id
WHERE c.categoryid = 4 AND
vc.category in ('color', 'size', 'shape');
You probably don't need the distinct, but that depends on the data. The left join is unnecessary because you are filtering on the second table in the where.
A simple rule: Never use commas in the from clause. To help, MySQL has scoping rules that can cause queries to break when you mix implicit and explicit join syntax.
The problem was a misspelled field on the table varietycategory, which I named
vcid, when I almost always name my table primary key id's "id".
Let's say I have two tables, and both their primary identifiers use the name 'id'. If I want to perform a join with these two tables, how would I alias the id of the table that I want to join with the former table?
For example:
SELECT * FROM `sites_indexed` LEFT JOIN `individual_data` ON `sites_indexed`.`id` = `individual_data`.`site_id` WHERE `url` LIKE :url
Now, site_id is supposed to link up with sites_indexed.id. The actual id which represents the row for individual_data however has the same title as sites_indexed.
Personally, I like to just use the name id for everything, as it keeps things consistent. When scripting server-side however, it can make things confusing.
e.g.
$var = $result['id'];
Given the aforementioned query, wouldn't this confuse the interpreter?
Anyway, how is this accomplished?
Instead of selecting all fields with "SELECT *" you should explicitly name each field you need, aliasing them with AS as required. For example:
SELECT si.field1 as si_field1,
si.field2 as si_field2,
ind_data.field1 as ind_data_field1
FROM sites_indexed as si
LEFT JOIN individual_data as ind_data
ON si.id = ind_data.site_id
WHERE `url` LIKE :url
And then you can reference the aliased names in your result set.
This thread is old and i found because i had the same problem. Now i have a better solution.
The answer given by Paul McNett and antun forces you to list all fields but in some cases this is impossible (too much fields to list), so you can keep the * and alias only the fields you want (typically the fields that have the same name and will override each other).
Here's how :
SELECT *, t.myfield as myNewName
FROM table t ... continue your query
you can add as much aliases as you want by adding comas.
Using this expression you will get results with columns id (from table sites_indexed) and id2 (alias for column id from table individual_data)
SELECT t1 . *, t2 . * FROM sites_indexed t1
LEFT JOIN (select id as id2, other_field1, other_field2 FROM individual_data) t2 ON t1.id = t2.site_id WHERE your_statement
The problem is that you're using the * wildcard. If you explicitly list the column names in your query, you can give them aliases:
SELECT `sites_indexed`.`id` AS `sites_indexed_id`,
`individual_data`.`id` AS `individual_data_id`
FROM `sites_indexed`
LEFT JOIN `individual_data` ON `sites_indexed`.`id` = `individual_data`.`site_id`
WHERE `url` LIKE :url
Then you can reference them via the alias:
$var = $result['sites_indexed_id'];
$var_b = $result['individual_data_id'];
How I can select name of creator and editor from users table, creator and editor are different ids in same table, but user table is different table
Is it what you mean?
$sql = "
SELECT id,name
FROM users
WHERE users.id = editors_table.$editor_id
OR users.id = creators_table.$creator_id";
from what i understand, are you saying you have 3 tables - 1 with creator data, 1 with editor data, and a third that references a record in each of the tables using an id?
if so, you'll have to use JOINs to achieve what you want - something like:
SELECT id, name, editors_table.editor_id, creators_table.creator_id
FROM users
LEFT JOIN editors_table ON user.editor_id = editor_table.editor_id
LEFT JOIN creators_table ON user.creator_id = creator_table.creator_id
WHERE editor_table.editor_id = $editor_id_var
OR creator_table.creator_id = $creator_id_var
(you'll want to go through the query as I'm guessing here)
I'm trying to create an "AssociateWith" data load option for my context to filter rows that the current user has access to. My simple data model is as such:
Tables
UserPermissions
PK: ID
FK: RelatedUserID nullable
FK: RelatedItemID not nullable
Users
PK: ID
Items
PK: ID
FK: RelatedCategoryID not nullable
Categories
PK: ID
On my datacontext, I'm trying to do something like:
//dbContext is my LINQ context
//current_user_id is the id of my current logged in user
var dlo = new DataLoadOptions();
//issue->UsersPermissions is one->many relationship
// if I omit this LoadWith line, no associatewith filter
// is created in the generated sql code
dlo.LoadWith<Items>(i=>i.UserPermissions);
dlo.AssociateWith<Items>(i=>
i.UserPermissions.Where(p=>
p.RelatedUserID.HasValue && p.RelatedUserID.Value == current_users_id));
dbContext.LoadOptions = dlo;
Everything seems reasonable to me, but the query generated in SQL looks like this:
SELECT [t0].[ID], [t1].[ID] AS [ID2], [t1].[RelatedUserID], [t1].[RelatedItemID]
(SELECT COUNT(*)
FROM [dbo].[UserPermissions] AS [t2]
WHERE (([t2].[RelatedUserID] = #p0)) AND ([t2].[RelatedItemID] = [t0].[ID])
) AS [value]
FROM [dbo].[Items] AS [t0]
LEFT OUTER JOIN [dbo].[UserPermissions] AS [t1] ON ([t1].[RelatedUserID] = #p0)
AND
([t1].[RelatedItemID] = [t0].[ID])
ORDER BY [t0].[ID], [t1].[ID]
How can I force an INNER JOIN instead of the LEFT OUTER JOIN? Am I modeling my relationship incorrectly on the backend?
Thanks for any help.
MMAS
LINQ to SQL generates the LEFT OUTER JOIN simply because UserPermissions.RelatedUserID column is nullable. The underlying LINQ provider just isn't 'smart' enough to further optimize that query to a simple INNER JOIN. I don't think there is anything you can do about this.