Search Results

Search found 6841 results on 274 pages for 'outer join'.

Page 8/274 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • MySQL LEFT JOIN, INNER JOIN etc, complicated query, PHP + MySQL for a forum

    - by Sven Eriksson
    So I've got a little forum I'm trying to get data for, there are 4 tables, forum, forum_posts, forum_threads and users. What i'm trying to do is to get the latest post for each forum and giving the user a sneak peek of that post, i want to get the number of posts and number of threads in each forum aswell. Also, i want to do this in one query. So here's what i came up with: SELECT lfx_forum_posts.*, lfx_forum.*, COUNT(lfx_forum_posts.pid) as posts_count, lfx_users.username, lfx_users.uid, lfx_forum_threads.tid, lfx_forum_threads.parent_forum as t_parent, lfx_forum_threads.text as t_text, COUNT(lfx_forum_threads.tid) as thread_count FROM lfx_forum LEFT JOIN (lfx_forum_threads INNER JOIN (lfx_forum_posts INNER JOIN lfx_users ON lfx_users.uid = lfx_forum_posts.author) ON lfx_forum_threads.tid = lfx_forum_posts.parent_thread AND lfx_forum_posts.pid = (SELECT MAX(lfx_forum_posts.pid) FROM lfx_forum_posts WHERE lfx_forum_posts.parent_forum = lfx_forum.fid GROUP BY lfx_forum_posts.parent_forum) ) ON lfx_forum.fid = lfx_forum_posts.parent_forum GROUP BY lfx_forum.fid ORDER BY lfx_forum.fid ASC This get the latest post in each forum and gives me a sneakpeek of it, the problem is that lfx_forum_posts.pid = (SELECT MAX(lfx_forum_posts.pid) FROM lfx_forum_posts WHERE lfx_forum_posts.parent_forum = lfx_forum.fid GROUP BY lfx_forum_posts.parent_forum) Makes my COUNT(lfx_forum_posts.pid) go to one (aswell as the COUNT(lfx_forum_threads.tid) which isn't how i would like it to work. My question is: is there some somewhat easy way to make it show the correct number and at the same time fetch the correct post info (the latest one that is)? If something is unclear please tell and i'll try to explain my issue further, it's my first time posting something here.

    Read the article

  • MYSQL JOIN WHERE ISSUES - need some kind of if condition

    - by Breezer
    Hi Well this will be hard to explain but ill do my best The thing is i have 4 tables all with a specific column to relate to eachother. 1 table with users(agent_users) , 1 with working hours(agent_pers), 1 with sold items(agent_stat),1 with project(agent_pro) the user and the project table is irrelevant in the issue at hand but to give you a better understanding why certain tables is included in my query i decided to still mention them =) The thing is that I use 2 pages to insert data to the working hour and the sold items during that time tables, then i have a third page to summarize everything for current month, the query for that is as following: SELECT *, SUM(sv_p_kom),SUM(sv_p_gick),SUM(sv_p_lunch) FROM (( agent_users LEFT JOIN agent_pers ON agent_users.sv_aid = agent_pers.sv_p_uid) LEFT JOIN agent_stat ON agent_pers.sv_p_uid = agent_stat.sv_s_uid) LEFT JOIN agent_pro ON agent_pers.sv_p_pid=agent_pro.p_id WHERE MONTH(agent_pers.sv_p_datum) =7 GROUP BY sv_aname so the problem is now that i dont want sold items from previous months to get included in the data received, i know i could solve that by simple adding in the WHERE part MONTH(agent_stat.sv_s_datum) =7 but then if no items been sold that month no data at all will show up not the time or anything. Any aid on how i could solve this is greatly appreciated. if there's something that's not so clear dont hesitate to ask and ill try my best to answer. after all my english isn't the best out there :P regards breezer

    Read the article

  • IS NULL doesn't work as expected in MSSQL 2000 with no Service Pack on it

    - by user306825
    The following batch executed on different instances of mssql 2000 illustrates the problem. select @@version create table a (a int) create table b (b int) insert into a(a) values (1) insert into a(a) values (2) insert into a(a) values (3) insert into b(b) values (1) insert into b(b) values (2) select * from a left outer join (select 1 as test, b from b) as j on j.b = a.a where j.test IS NULL drop table a drop table b Output 1: Microsoft SQL Server 2000 - 8.00.194 (Intel X86) Aug 6 2000 00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Developer Edition on Windows NT 6.1 (Build 7600: ) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) a test b (0 row(s) affected) Output 2: Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 2) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) a test b 3 NULL NULL (1 row(s) affected) If someone encounters the same problem - make sure you have the SP installed!

    Read the article

  • Filtering on a left join in SQLalchemy

    - by Adam Ernst
    Using SQLalchemy I want to perform a left outer join and filter out rows that DO have a match in the joined table. I'm sending push notifications, so I have a Notification table. This means I also have a ExpiredDeviceId table to store device_ids that are no longer valid. (I don't want to just delete the affected notifications as the user might later re-install the app, at which point the notifications should resume according to Apple's docs.) CREATE TABLE Notification (device_id TEXT, time DATETIME); CREATE TABLE ExpiredDeviceId (device_id TEXT PRIMARY KEY, expiration_time DATETIME); Note: there may be multiple Notifications per device_id. There is no "Device" table for each device. So when doing SELECT FROM Notification I should filter accordingly. I can do it in SQL: SELECT * FROM Notification LEFT OUTER JOIN ExpiredDeviceId ON Notification.device_id = ExpiredDeviceId.device_id WHERE expiration_time == NULL But how can I do it in SQLalchemy? sess.query( Notification, ExpiredDeviceId ).outerjoin( (ExpiredDeviceId, Notification.device_id == ExpiredDeviceId.device_id) ).filter( ??? ) Alternately I could do this with a device_id NOT IN (SELECT device_id FROM ExpiredDeviceId) clause, but that seems way less efficient.

    Read the article

  • What is so bad about using SQL INNER JOIN

    - by Stephen B. Burris Jr.
    Everytime a database diagram gets looked out, one area people are critical of is inner joins. They look at them hard and has questions to see if an inner join really needs to be there. Simple Library Example: A many-to-many relationship is normally defined in SQL with three tables: Book, Category, BookCategory. In this situation, Category is a table that contains two columns: ID, CategoryName. In this situation, I have gotten questions about the Category table, is it need? Can it be used as a lookup table, and in the BookCategory table store the CategoryName instead of the CategoryID to stop from having to do an additional INNER JOIN. (For this question, we are going to ignore the changing, deleting of any CategoryNames) The question is, what is so bad about inner joins? At what point is doing them a negative thing (general guidelines like # of transactions, # of records, # of joins in a statement, etc)?

    Read the article

  • Join query in doctrine symfony

    - by THOmas
    I have two tables userdetails and blog question The schema is UserDetails: connection: doctrine tableName: user_details columns: id: type: integer(8) fixed: false name: type: string(255) fixed: false BlogQuestion: connection: doctrine tableName: blog_question columns: question_id: type: integer(8) fixed: false unsigned: false primary: true autoincrement: true blog_id: type: integer(8) fixed: false user_id: type: integer(8) fixed: false question_title: type: string(255) I am using one join query for retrieving all the questions and user details from this two tables My join query is $q = Doctrine_Query::create() ->select('*') ->from('BlogQuestion u') ->leftJoin('u.UserDetails p'); $q->execute(); But it is showing this error Unknown relation alias UserDetails Pls anybody help me Thanks in advance

    Read the article

  • LINQ to SQL join when there aren't results

    - by Boarder2
    Given the following database structure I'm trying to write a LINQ query that will return images grouped by tags it's associated with. So far I've got this: var images = from img in db.Images join imgTags in db.ImageTags on img.idImage equals imgTags.idImage join t in db.Tags on imgTags.idTag equals t.idTag where img.OCRData.Contains(searchText.Text) group img by new { t.TagName } into aGroup select new { GroupName = aGroup.Key.TagName, Items = from x in aGroup select new ImageFragment() { ImageID = x.idImage, ScanDate = x.ScanTime } }; Which works great. However, I also want to return Images that do not have any tags associated with them in a group of "(Untagged)" or something. I can't wrap my head around how I would do this without inserting a default tag for every image and that seems like generally not a very good solution.

    Read the article

  • [Newbie] How to join mysql tables

    - by Ivan
    I've an old table like this: user> id | name | address | comments And now I've to create an "alias" table to allow some users to have an alias name for some reasons. I've created a new table 'user_alias' like this: user_alias> name | user But now I have a problem due my poor SQL level... How to join both tables to generate something like this: 1 | my_name | my_address | my_comments 1 | my_alias | my_address | my_comments 2 | other_name | other_address | other_comments I mean, I want to make a "SELECT..." query that returns in the same format as the "user" table ALL users and ALL alias.. Something like this: SELECT user.* FROM user LEFT JOIN user_alias ON `user`=`id` but it doesn't work for me..

    Read the article

  • How to join mysql tables

    - by Ivan
    I've an old table like this: user> id | name | address | comments And now I've to create an "alias" table to allow some users to have an alias name for some reasons. I've created a new table 'user_alias' like this: user_alias> name | user But now I have a problem due my poor SQL level... How to join both tables to generate something like this: 1 | my_name | my_address | my_comments 1 | my_alias | my_address | my_comments 2 | other_name | other_address | other_comments I mean, I want to make a "SELECT..." query that returns in the same format as the "user" table ALL users and ALL alias.. Something like this: SELECT user.* FROM user LEFT JOIN user_alias ON `user`=`id` but it doesn't work for me..

    Read the article

  • SQL Join a View with a Table

    - by gamerzfuse
    CREATE VIEW qtyorderedview AS SELECT titleditors.title_id, titleditors.ed_id, salesdetails.title_id, salesdetails.qty_shipped FROM titleditors, salesdetails WHERE titleditors.title_id = salesdetails.title_id I am using the above SQL statement to create a view. I need to show Editors First Name, Last Name, City where they shipped more than 50 books. The three tables I have are: create table editors ( ed_id char(11), ed_lname varchar(20), ed_fname varchar(20), ed_pos varchar(12), phone varchar(10), address varchar(30), city varchar(20), state char(2), zip char(5), ed_boss char(11)); create table titleditors ( ed_id char(11), title_id char(6), ed_ord integer); create table salesdetails ( sonum integer, qty_ordered integer, qty_shipped integer, title_id char(6), date_shipped date); Can anyone tell me what the second Join code would be to create this result? My first view works fine, but I don't know how to join it to the second table to achieve this result? I didn't make the tables, I just have to work with what I was given. Thanks in advance!

    Read the article

  • SQL: many-to-many relationship, IN condition

    - by Maarten
    I have a table called transactions with a many-to-many relationship to items through the items_transactions table. I want to do something like this: SELECT "transactions".* FROM "transactions" INNER JOIN "items_transactions" ON "items_transactions".transaction_id = "transactions".id INNER JOIN "items" ON "items".id = "items_transactions".item_id WHERE (items.id IN (<list of items>)) But this gives me all transactions that have one or more of the items in the list associated with it and I only want it to give me the transactions that are associated with all of those items. Any help would be appreciated.

    Read the article

  • django left join with null

    - by SledgehammerPL
    The model: class Product(models.Model): name = models.CharField(max_length = 128) def __unicode__(self): return self.name class Receipt(models.Model): name = models.CharField(max_length=128) components = models.ManyToManyField(Product, through='ReceiptComponent') class Admin: pass def __unicode__(self): return self.name class ReceiptComponent(models.Model): product = models.ForeignKey(Product) receipt = models.ForeignKey(Receipt) quantity = models.FloatField(max_length=9) unit = models.ForeignKey(Unit) def __unicode__(self): return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive The idea: there are a components on stock. I'd like to find out which recipes I can made with components which I have. It's not easy - but possible - I made a SQL view, which gets the solution. But I'm learning python and Django so I'd like to make it Django-style ;D The concept of solution: get the set of recipes which has at last one component: list_of_available_components = ReceiptComponent.objects.filter(product__in=list_of_available_products).distinct() list_of_related_receipts = Receipt.objects.filter(receiptcomponent__in = list_of_available_components).distinct() get recipes (from list_of_related_receipts) which has not at last one component list_of_incomplete_recipes = (SELECT * FROM drinkbook_receiptcomponent LEFT JOIN drinkstore_stock_products USING(product_id) WHERE drinkstore_stock_products.stock_id IS NULL AND receipt_id IN (SELECT receipt_id FROM drinkbook_receiptcomponent JOIN drinkstore_stock_products USING(product_id))) get recipes (from list_of_related_receipts) which are not in "list_of_incomplete_recipes"

    Read the article

  • mySQL Query JOIN in same table

    - by jeerose
    Table structure goes something like this: Table: Purchasers Columns: id | organization | city | state Table: Events Columns: id | purchaser_id My query: SELECT purchasers.*, events.id AS event_id FROM purchasers INNER JOIN events ON events.purchaser_id = purchasers.id WHERE purchasers.id = '$id' What I would like to do, is obviously to select entries by their id from the purchasers table and join from events. That's the easy part. I can also easily to another query to get other purchasers with the same organization, city and state (there are multiples) but I'd like to do it all in the same query. Is there a way I can do this? In short, grab purchasers by their ID but then also select other purchasers that have the same organization, city and state. Thanks.

    Read the article

  • Join a single row in one table to n random rows in another

    - by Einar Egilsson
    Is it possible to make a join in SQL server that joins each row from table A to n random rows in another? For example, say I have a Customer table, a Product table and an Order table. I want to join each customer to 5 random products and insert these rows into the order table. (And each customer should be joined to 5 random rows of his own, I don't want all customers joining to the same 5 rows). Is this possible? I'm using SQL Server 2005 and it's fine if the solution is specific to that. This is a weird requirement but I'm basically making a small data generator to generate some random data.

    Read the article

  • SELECT subset from two tables and LEFT JOIN results

    - by Doctor Trout
    Hi all, I'm trying to write a bit of SQL for SQLITE that will take a subset from two tables (TableA and TableB) and then perform a LEFT JOIN. This is what I've tried, but this produces the wrong result: Select * from TableA Left Join TableB using(key) where TableA.key2 = "xxxx" AND TableB.key3 = "yyyy" This ignore cases where key2="xxxx" but key3 != "yyyy". I want all the rows from TableA that match my criteria whether or not their corresponding value in TableB matches, but only those rows from TableB that match both conditions. I did manage to solve this by using a VIEW, but I'm sure there must be a better way of doing this. It's just beginning to drive me insane tryng to solve it now. (Thanks for any help, hope I've explained this well enough).

    Read the article

  • How can I join on a CSV varchar?

    - by mgroves
    I have a varchar field that contains a string like "10,11,12,13". How can I use that CSV string to join to another table with those IDs? Here's the approach I'm taking now: select * from SomeTable a WHERE (',' + @csvString + ',') LIKE '%,' + CONVERT(varchar(25), a.ID) + ',%' Where @csvString is "10,11,12,...". I intend to use this method as a join condition as well. That method works, but it's rather slow (using CAST doesn't improve the speed). I understand that having CSVs in the database like that is usually a very silly idea in most cases, but there's nothing I can do about that.

    Read the article

  • Need some help with a join on ContentProviders

    - by Pentium10
    The documentation says Columns from the associated aggregated contact are also available through an implicit join. What's that implicit join? `Join with Contacts` String LOOKUP_KEY read-only See ContactsContract.Contacts String DISPLAY_NAME read-only See ContactsContract.Contacts long PHOTO_ID read-only See ContactsContract.Contacts. int IN_VISIBLE_GROUP read-only See ContactsContract.Contacts. int HAS_PHONE_NUMBER read-only See ContactsContract.Contacts. I am querying ContactsContract.Data, and I need to access as where clauses on the query IN_VISIBLE_GROUP and HAS_PHONE_NUMBER, that are defined in ContactsContract.Contacts. How can I make this possible?

    Read the article

  • SQL LEFT JOIN help

    - by Stolz
    My scenario: There are 3 tables for storing tv show information; season, episode and episode_translation. My data: There are 3 seasons, with 3 episodes each one, but there is only translation for one episode. My objetive: I want to get a list of all the seasons and episodes for a show. If there is a translation available in a specified language, show it, otherwise show null. My attempt to get serie 1 information in language 1: SELECT season_number AS season,number AS episode,name FROM season NATURAL JOIN episode NATURAL LEFT JOIN episode_trans WHERE id_serie=1 AND id_lang=1 ORDER BY season_number,number result: +--------+---------+--------------------------------+ | season | episode | name | +--------+---------+--------------------------------+ | 3 | 3 | Episode translated into lang 1 | +--------+---------+--------------------------------+ expected result +-----------------+--------------------------------+ | season | episode| name | +-----------------+--------------------------------+ | 1 | 1 | NULL | | 1 | 2 | NULL | | 1 | 3 | NULL | | 2 | 1 | NULL | | 2 | 2 | NULL | | 2 | 3 | NULL | | 3 | 1 | NULL | | 3 | 2 | NULL | | 3 | 3 | Episode translated into lang 1 | +--------+--------+--------------------------------+ Full DB dump http://pastebin.com/Y8yXNHrH

    Read the article

  • 2 Select or 1 Join query ?

    - by xRobot
    I have 2 tables: book ( id, title, age ) ---- 100 milions of rows author ( id, book_id, name, born ) ---- 10 millions of rows Now, supposing I have a generic id of a book. I need to print this page: Title: mybook authors: Tom, Graham, Luis, Clarke, George So... what is the best way to do this ? 1) Simple join like this: Select book.title, author.name From book, author WHERE ( author.book_id = book.id ) AND ( book.id = 342 ) 2) For avoid the join, I could make 2 simple query: Select title FROM book WHERE id = 342 Select name FROM author WHERE book_id = 342 What is the most efficient way ?

    Read the article

  • MySQL Join issue

    - by mouthpiec
    Hi, I have the following tables: --table sportactivity-- sport_activity_id, home_team_fk, away_team_fk, competition_id_fk, date, time (tuple example) - 1, 33, 41, 5, 2010-04-14, 05:40:00 --table teams-- team_id, team_name (tuple example) - 1, Algeria Now I have the following SQL statment that I use to extract Team A vs Team B SELECT sport_activity_id, T1.team_name AS TeamA, T2.team_name AS TeamB, DATE_FORMAT( DATE, '%d/%m/%Y' ) AS DATE, DATE_FORMAT( TIME, '%H:%i' ) AS TIME FROM sportactivity JOIN teams T1 ON home_team_fk = T1.team_id JOIN teams T2 ON ( away_team_fk = T2.team_id OR away_team_fk = '0' ) WHERE DATE( DATE ) >= CURDATE( ) ORDER BY DATE( DATE ) My problem is that when team B is empty, I am having irrelevant information .... it seems that it is returning all the combinations. I need a query that when team B is equal to 0, (this can occur in my scenario) I get only Team A - Team B (as 0) once.

    Read the article

  • mysql join with a "bounce" off a third table

    - by Enkay
    I have 3 mysql tables. companies with company_id and company_name products with product_id and company_id names with product_id, product_name and other info about the product I'm trying to output the product_name and the company_name in one query for a given product_id. Basically I need information from the names and companies tables and the link between them is the products table. How do I do a join that needs to "bounce" off a third table? Something like this but this obviously doesn't work : SELECT product_name, company_name FROM names LEFT OUTER JOIN companies ON (names.product_id = products.product_id and products.company_id = companies.company_id) WHERE product_id = '12345' Thanks!

    Read the article

  • group_concat on an empty join in MySQL

    - by Yossarian
    Hello, I've got the following problem: I have two tables: (simplified) +--------+ +-----------+ | User | | Role | +--------+ +-----------+ | ID<PK> | | ID <PK> | +--------+ | Name | +-----------+ and M:N relationship between them +-------------+ | User_Role | +-------------+ | User<FK> | | Role<FK> | +-------------+ I need to create a view, which selects me: User, and in one column, all of his Roles (this is done by group_concat). I've tried following: SELECT u.*, group_concat(r.Name separator ',') as Roles FROM User u LEFT JOIN User_Role ur ON ur.User=u.ID LEFT JOIN Role r ON ur.Role=r.ID GROUP BY u.ID; However, this works for an user with some defined roles. Users without role aren't returned. How can I modify the statement, to return me User with empty string in Roles column when User doesn't have any Role? Explanation: I'm passing the SQL data directly to a grid, which then formats itself, and it is easier for me to create slow and complicated view, than to format it in my code. I'm using MySQL

    Read the article

  • Oracle curcular join sometimes give duplicates, but sometimes does not

    - by Kaushik
    By mistake I wrote a query like this: select * from a,b,c where a.col=b.col and b.col2=c.col2 and c.col3=a.col4 So there is a circular join here. Now the thing is sometimes this query returns duplicate result, sometimes it returns unique(correct) results. I am trying to understand why it does not give duplicate results always. Also if circular joins are not allowed, how come Oracle does not throw an error. EDIT: This is the actual query. After reading ti carefully, I am not sure anymore if this is a circular join or not.It does not seem so...but why I get duplicates only sometime? select * from a,b,c,d where a.col=b.col and b.col=c.col and c.col2=d.col2 and d.col2 =a.col2

    Read the article

  • Broken count(*) after adding LEFT JOIN

    - by Iain Urquhart
    Since adding the LEFT JOIN to the query below, the count(*) has been returning some strange values, it seems to have added the total rows returned in the query to the 'level': SELECT `n`.*, exp_channel_titles.*, round((`n`.`rgt` - `n`.`lft` - 1) / 2, 0) AS childs, count(*) - 1 + (`n`.`lft` > 1) + 1 AS level, ((min(`p`.`rgt`) - `n`.`rgt` - (`n`.`lft` > 1)) / 2) > 0 AS lower, (((`n`.`lft` - max(`p`.`lft`) > 1))) AS upper FROM `exp_node_tree_6` `n` LEFT JOIN `exp_channel_titles` ON (`n`.`entry_id`=`exp_channel_titles`.`entry_id`), `exp_node_tree_6` `p`, `exp_node_tree_6` WHERE `n`.`lft` BETWEEN `p`.`lft` AND `p`.`rgt` AND ( `p`.`node_id` != `n`.`node_id` OR `n`.`lft` = 1 ) GROUP BY `n`.`node_id` ORDER BY `n`.`lft` I'm totally stumped... Thank you!

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >