Have seen multiple posts on this but I can't see any which answer my question.
Basically I have 3 tables in my database which relate to members and their categorisation/classification.
members (defines list of members and associated data)
member_taxonomy (defines categories, subcategories and facilities using combination of partent id and enumerated field tax_type (CATEGORY, SUBCATEGORY, FACILITY)
member_taxonomy_map (defines mapping between members and member_taxonomy)
I have a members page within which are a number of options to refine the search by specifying one or more subcategory and one or more facility. I have been trying to search on the table using the query:
SELECT members.*
FROM (members)
JOIN member_taxonomy_map ON member_taxonomy_map.member_id = members.id
WHERE member_taxonomy_map.taxonomy_id = 1
AND member_taxonomy_map.taxonomy_id = 26
AND members.active = 1
AND members.deleted = 0;
However this returns 0 rows which is something to do with having multiple where clauses on the same column but I can't figure out how this query should look. Each time the search is refined (and there could be up to 30 different options to refine the search) I need add an additional AND clause so that only members with these mappings are returned.
An IN clause will not work as this is effectively returning any rows which match any of these particular values but this is incorrect as it needs to match exactly the values specified.
Hopefully someone can give me a few pointers in the right direction.
Thanks in advance.
UPDATE
It is possible that taxonomy_id can be 1 and 26. I prob need to include the schema for the members_taxonomy_map table.
id int
tax_name varchar
slug varchar
tax_type enum ('CATEGORY','CLASSIFICATION','FACILITY','RATING')
parent_id int
active int
Therefore any tax_type with no parent id set are top level CATEGORY. Subcategories have a parent_id CATEGORY. CLASSIFICATION's can have a parent_id of the CATEGORY and FACILITY's have a parent_id of CATEGORY.
Therefore for example a category could be accommodation, sub-category could be hotel and facility could be wifi. Therefore if a member has all three of these items they will have 3 entries in the mapping table. I need to be be able to filter these so that it builds up the query to filter depending on the accommodation types (i.e subcategories - those entries with a tax_type of CATEGORY but also have a parent id, then within this the classifications. The query may return multiple entries for the same member but I can deal with this by filter these out with extra SQL clauses.
SELECT members.*
FROM (members)
JOIN member_taxonomy_map ON member_taxonomy_map.member_id = members.id
WHERE (member_taxonomy_map.taxonomy_id = 1
OR member_taxonomy_map.taxonomy_id = 26)
AND members.active = 1
AND members.deleted = 0;
It's probably not possible for a record to have a taxonomy_id of 1 and 26; you are probably trying to get a record that contains one or the other.
SELECT mb.*
FROM members mb
JOIN member_taxonomy_map tm ON tm.member_id = mb.id
WHERE tm.taxonomy_id IN ( 1, 26)
AND mb.active = 1
AND mb.deleted = 0
;
... Or ...
SELECT mb.*
FROM members mb
WHERE EXISTS ( SELECT *
FROM member_taxonomy_map tm
WHERE ON tm.member_id = mb.id
AND tm.taxonomy_id IN ( 1, 26)
)
AND mb.active = 1
AND mb.deleted = 0
;
... Or ...
SELECT mb.*
FROM members mb
WHERE mb.id IN ( SELECT tm.member_id
FROM member_taxonomy_map tm
WHERE tm.taxonomy_id IN ( 1, 26)
)
AND mb.active = 1
AND mb.deleted = 0
;
You need to JOIN member_taxonomy_map for every taxonomy_id
SELECT members.*
FROM members
JOIN member_taxonomy_map mtm1 ON mtm1.member_id = members.id AND mtm1.taxonomy_id=1
JOIN member_taxonomy_map mtm26 ON mtm26.member_id = members.id AND mtm26.taxonomy_id=26
WHERE members.active = 1
AND members.deleted = 0;
Related
I have two tables:-
gallery
gallery_favorite
The user_id in gallery table means the user who posted the item. The user_id in gallery_favorite means the user who added the item in his favorite list. If favorite = 0, then it means the user had initially added the item in favorite list but later removed it.
Now, I want to fetch all the gallery items along with its favorite status. Here is my query:-
Select distinct `gallery`.`id`, `gallery`.`caption`, `gallery`.`type`,
`gallery`.`video`, `gallery`.`image`, `gallery`.`type`,
`gallery`.`created_date`, `gallery`.`modified_date`,
`gallery_favorite`.`favorite`, `gallery`.`user_id`
from `gallery`
left join `gallery_favorite` on `gallery_favorite`.`gallery_id` = `gallery`.`id`
where
(`gallery`.`type` = 'i'
and `gallery`.`status` = 1
and `gallery`.`deleted` = 0)
and
((`gallery`.`user_id` != 11 and `gallery`.`private` = 0)
or `gallery`.`user_id` = 11)
limit 20 offset 0
But a syou can see, I am getting duplicate records depending upon the number of rows wrt to a gallery item in the gallery favorite table. How can I modify the query to get only one record (along with my own favorite status)?
I guess you are getting duplicate records because you have not joined both the table on user_id -
Try below query -
Select distinct `gallery`.`id`, `gallery`.`caption`, `gallery`.`type`,
`gallery`.`video`, `gallery`.`image`, `gallery`.`type`,
`gallery`.`created_date`, `gallery`.`modified_date`,
`gallery_favorite`.`favorite`, `gallery`.`user_id`
from `gallery`
left join `gallery_favorite` on `gallery_favorite`.`gallery_id` = `gallery`.`id`
and `gallery_favorite`.`user_id` = `gallery`.`user_id`
where
(`gallery`.`type` = 'i'
and `gallery`.`status` = 1
and `gallery`.`deleted` = 0)
and
((`gallery`.`user_id` != 11 and `gallery`.`private` = 0)
or `gallery`.`user_id` = 11)
limit 20 offset 0
Assuming the gallery as many favorites from different users. It makes no sense to display exclusively a hit favorite to a user and gallery alone. Counting them makes sense.
Select `gallery`.`id`, `gallery`.`caption`, `gallery`.`type`,
`gallery`.`video`, `gallery`.`image`, `gallery`.`type`,
`gallery`.`created_date`, `gallery`.`modified_date`,
sum(gallery_favorite`.`favorite`) as total_favorites -- count them group function aggregate
from `gallery`
left join `gallery_favorite` on `gallery_favorite`.`gallery_id` = `gallery`.`id`
where
(`gallery`.`type` = 'i'
and `gallery`.`status` = 1
and `gallery`.`deleted` = 0)
and
((`gallery`.`user_id` != 11 and `gallery`.`private` = 0)
or `gallery`.`user_id` = 11)
and gallery_favorite`.`favorite` = 1 -- count only the favorites
GROUP BY `gallery`.`id` -- GROUP CLAUSE
This is how a join works. You get all rows matching the condition. You can either group the result by the fields in the left table (thus eliminating duplicates in the output) or join with a table that has one entry per gallery item -- this requires joining with a (SELECT ... FROM gallery_favorite GROUP BY gallery_id)
It was hard to come up with a good title for this one. I have a query selecting products from my table. Each product may belong to multiple categories. So when I add in the 'category' to my DISTINCT query, it sometimes returns multiple of the same product because that product belongs to more than one category. I want my query to just pick one of the categories and return that, doesn't matter which one.
Here is my query:
SELECT DISTINCT ci.NAME,
ci.pid,
ci.description,
ci.price,
ci.saleprice,
ci.ingredients,
ci.allergens AS allergens,
ci.isfood,
ci.quantity,
ci.ismostpopular,
ci.activedate,
ci.isfrozen,
cc.NAME AS category
FROM cart_category cc
JOIN cart_item_category cic
ON cc.id = cic.catid
JOIN cart_item ci
ON cic.itemref = ci.itemref
WHERE cc.active = 1
AND ci.active = 1
AND ci.isdeleted = 0
AND ci.isfrozen = 0
AND ( ci.NAME LIKE '%dark%'
OR ci.pid = '%dark%' )
AND ci.quantity > 5
AND cc.NAME <> "nutritionals";
When I add in cc.name as category is when it returns multiple of the same product.
try just to limit it:
... LIMIT 1
I have two table in database.
1) tbl_lab_checkup
2) tbl_lab
tbl_lab has all the records of laboratories and tbl_lab_checkup has all the records o checkup that lab provides.
Following are the fields in tables
1) tbl_lab_checkup
-- labcheckupid (pk)
-- labid (fk)
-- checkupid (fk)
-- cost
-- discount
2) tbl_lab
-- labid (pk)
-- labname
-- labarea (fk)
I have 'areaid'=1 and 'checkupid' in array which I contact with "," (1,2).
What I want is to get all the lablist available in areaid=1 who provides all the checkup in an array (1,2)
I tried following query But Im getting wrong result.
SELECT tlc .* FROM tbl_lab_checkup tlc
INNER JOIN tbl_lab lb ON
tlc.labid = lb.labid
WHERE
tlc.checkupid IN (1,2) AND lb.labarea=1
GROUP BY lb.labid
It return result even if lab provides only one id in array. Anyone have solution for this.
Check fiddle : http://sqlfiddle.com/#!2/5c674/1
If you have building this query then you can add the having clause like following:
SELECT tlc .* FROM tbl_lab_checkup tlc
INNER JOIN tbl_lab lb ON
tlc.labid = lb.labid
WHERE
tlc.checkupid IN (1,2) AND lb.labarea=1
GROUP BY lb.labid
having count(tlc.checkupid) = 2;
Here having count(tlc.checkupid) = 2; the value 2 is the count of your elements in tlc.checkupid IN (1,2).
And if you'd like distinct tlc.checkupid, you could switch the having count(tlc.checkupid) = 2 to having count(distinct tlc.checkupid) = 2;
I would generally go with the suggestion above by vinodadhikary, but another option would be to use one JOIN per check:-
SELECT lb.*
FROM tbl_lab lb
INNER JOIN tbl_lab_checkup tlc1 ON tlc1.labid = lb.labid AND tlc1.checkupid = 1
INNER JOIN tbl_lab_checkup tlc2 ON tlc2.labid = lb.labid AND tlc2.checkupid = 2
WHERE lb.labarea=1
This will work when you want all the tbl_lab_checkup record details
User this code to get your desired result in CI:
$this->db->select("tbl_lab.*");
$this->db->join("tbl_lab_checkup","tbl_lab_checkup.labid = tbl_lab.labid");
$this->db->where("tbl_lab.labarea","1");
$find="FIND_IN_SET('1,2','tbl_lab_checkup.checkupid')";
$this->db->where($find);
$this->db->get("tbl_lab");
i am trying to write the Query for three things .My table structure is like that
You can see Schema at http://sqlfiddle.com/#!2/56c2d/1
I am trying to write the query in MYSQL
user:- table
user_id
user_fname
This is User tabke which will save User Information
group:- "group" and "subgroup" is maintain in same table using column "group_parent_group_id"
group_id
group_title
group_parent_group_id(INT)
This is group table which will save Group and Subgroups
user_group: table
user_group_id
user_group_user_id
user_group_group_id
This ill store both User and Group relation using their Id
I am trying to write the Query for three things. Fetching Users Groups, Subgroups
1) Query to fetch list of All Groups for User Register. Query is gelow and is giving error
Query:
select user.id, user.user_fname, group.group_id, group.group_title
from `user`
inner join user_group on user_group.user_group_user_id = user.user_id
inner join group on group.group_id = user_group.user_group_group_id
where user_group.user_group_user_id = 1 and user_group.group_parent_group_id = 0
2) I am Looking the query to fetch all subgroups(For Whom user is already Register) for Group Id 1,2 or 1
3) I am Looking the query to fetch all subgroups(For Whom user is Not Register yet) for Group Id 1,2 or 1. Ideal is for giving him randomly suggest a subgroup to add
Please Help. I am a newbie in DB :(
Your query is probably failing as you have a table called group, which is a reserved word. You can use back tics to delimit the name to get away with this (as follows) but it would be a better idea to change the table name.
SELECT user.id, user.user_fname, `group`.group_id, `group`.group_title
FROM `user`
INNER JOIN user_group ON user_group.user_group_user_id = user.user_id
INNER JOIN `group` ON `group`.group_id = user_group.user_group_group_id
WHERE user_group.user_group_user_id = 1
AND user_group.group_parent_group_id = 0
EDIT updated for queries I think the OP requires.
First query will get a list of all the groups (ones that have no parent group id) that a user (in this case id 28) is a member of
SELECT y2m_user.user_id, y2m_user.user_first_name, y2m_group.group_id, y2m_group.group_title
FROM y2m_user
INNER JOIN y2m_user_group ON y2m_user_group.user_group_user_id = y2m_user.user_id
INNER JOIN y2m_group ON y2m_group.group_id = y2m_user_group.user_group_group_id
WHERE y2m_user.user_id = 28
AND y2m_group.group_parent_group_id = 0
This query will get a list of all the sub groups (ones where the parent group id is greater than 0) that a user (in this case id 28) is a member of
SELECT y2m_user.user_id, y2m_user.user_first_name, y2m_group.group_id, y2m_group.group_title
FROM y2m_user
INNER JOIN y2m_user_group ON y2m_user_group.user_group_user_id = y2m_user.user_id
INNER JOIN y2m_group ON y2m_group.group_id = y2m_user_group.user_group_group_id
WHERE y2m_user.user_id = 28
AND y2m_group.group_parent_group_id > 0
This query will get a list of all the sub groups (ones where the parent group id is greater than 0) that a user (in this case id 28) is NOT a member of
SELECT y2m_user.user_id, y2m_user.user_first_name, y2m_group.group_id, y2m_group.group_title
FROM y2m_user
CROSS JOIN y2m_group
LEFT OUTER JOIN y2m_user_group ON y2m_user_group.user_group_user_id = y2m_user.user_id AND y2m_group.group_id = y2m_user_group.user_group_group_id
WHERE y2m_user.user_id = 28
AND y2m_group.group_parent_group_id > 0
AND y2m_user_group.user_group_id IS NULL
Please excuse any typos as not tested (with your test data there are no sub groups).
I have this data in a table, for instance,
id name parent parent_id
1 add self 100
2 manage null 100
3 add 10 200
4 manage null 200
5 add 20 300
6 manage null 300
How can I left join or inner join this table itself so I get this result below?
id name parent
2 manage self
4 manage 10
6 manage 20
As you can I that I just want to query the row with the keyword of 'manage' but I want the column parent's data in add's row as the as in manage's row in the result.
Is it possible?
EDIT:
the simplified version of my actual table - system,
system_id parent_id type function_name name main_parent make_accessible sort
31 30 left main Main NULL 0 1
32 31 left page_main_add Add self 0 1
33 31 left page_main_manage Manage NULL 0 2
my actual query and it is quite messy already...
SELECT
a.system_id,
a.main_parent,
b.name,
b.make_accessible,
b.sort
FROM system AS a
INNER JOIN -- self --
(
SELECT system_id, name, make_accessible, sort
FROM system AS s2
LEFT JOIN -- search --
(
SELECT system_id AS parent_id
FROM system AS s1
WHERE s1.function_name = 'page'
) AS s1
ON s1.parent_id = s2.parent_id
WHERE s2.parent_id = s1.parent_id
AND s2.system_id != s1.parent_id
ORDER BY s2.sort ASC
) b
ON b.system_id = a.parent_id
WHERE a.function_name LIKE '%manage%'
ORDER BY b.sort ASC
result I get currently,
system_id main_parent name make_accessible sort
33 NULL Main 0 1
but I am after this,
system_id main_parent name make_accessible sort
33 self Main 0 1
You just need to reference the table twice:
select t1.id, t1.name, t2.id, t2.name
from TableA t1
inner join TableA t2
on t1.parent_id = t2.Id
Replace inner with left join if you want to see roots in the list.
UPDATE:
I misread your question. It seems to me that you always have two rows, manage one and add one. To get to "Add" from manage:
select system.*, (select parent
from system s2
where s2.parent_id = system.parent_id
and s2.name = 'add')
AS parent
from system
where name = 'manage'
Or, you might split the table into two derived tables and join them by parent_id:
select *
from system
inner join
(
select * from system where name = 'add'
) s2
on system.parent_id = s2.parent_id
where system.name = 'manage'
This will allow you to use all the columns from s2.
Your data does not abide to a child-parent hierarchical structure. For example, your column parent holds the value 10, which is not the value of any id, so a child-parent association is not possible.
In other words, there's nothing that relates the record 2,manage,null to the record 1,add,self, or the record 4,manage,null to 3,add,10, as you intend to do in your query.
To represent hierarchical data, you usually need a table that has a foreign key referencing it's own primary key. So your column parent must reference the column id, then you can express a child-parent relationship between manage and add. Currently, that's not possible.
UPDATED: Joining by parent_id, try:
select m.id, m.name, a.parent
from myTable m
join myTable a on m.parent_id = a.parent_id and a.name = 'add'
where m.name = 'manage'
Change the inner join to a left join if there may not be a corresponding add row.